2013-07-09 60 views
2

我正在使用Visual Studio,並且我想將我在文本框中的字符串轉換爲DateTime格式。我正在使用函數Convert.ToDateTime(),但返回的值是最小值(0/0/0001 00:00:00)。將字符串轉換爲日期時間返回最小值

什麼問題?

從我的文本框中檢索字符串的代碼。

//pass startdate end date to studentResult.aspx 
Session["startdate"] = txtStartDate.Text.ToString(); 
Session["enddate"] = txtEndDate.Text.ToString(); 

將字符串轉換爲日期時間格式的代碼。

string startdate = (string)(Session["startdate"]); 
string enddate = (string)(Session["enddate"]); 
DateTime one = Convert.ToDateTime(startdate); 
DateTime two = Convert.ToDateTime(enddate); 
+2

你是什麼'textbox'值的值,它會返回false? –

+0

你不能分享代碼嗎? – Kangkan

+1

您是否嘗試將文本框本身轉換爲DateTime或其文本屬性?即'Convert.ToDateTime(myTextBox)'或'Convert.ToDateTime(myTextBox.Text)' – Squid

回答

3

正如我commentConvert.ToDateTime方法指出返回DateTime.MinValue如果參數是null

Return Value 
Type: System.DateTime 
The date and time equivalent of the value of value, or the date and time equivalent of DateTime.MinValue if value is null. 

可能是你的參數是null但因爲你沒有給我們更多的細節,我們無法知道確切的問題是什麼。

作爲指揮員的錯誤,請確保您傳遞的參數.Text屬性TextBox,而不是自身。見Squid的comment

0

應用嘗試解析,如果發生任何轉換錯誤

Datetime @dateTime; 

if(DateTime.TryParse(txtStartDate.Text, out @dateTime)) { 
    return @dateTime; 
} 
相關問題