2015-09-03 42 views
-1

我正面臨有關類型轉換的問題。一個值來自數據庫存儲過程。我將這個值存儲在這個隱藏的字段中。將隱藏字段值轉換爲日期時間的例外

<asp:HiddenField id="hfScheduleDate" runat="server" value='<%#Eval("ScheduleDate") %>' /> 

並嘗試以這種方式轉換它。

DateTime Date = Convert.ToDateTime(hfScheduleDate.Value); 

現在它是例外。

字符串未被識別爲有效的DateTime。

+0

請您提供正試圖轉換爲datetime –

+0

日期時間scheduledate = Convert.ToDateTime(hfScheduleDate.Value) –

+0

我已經看到它在你的問題的字符串的一個例子。讓我看看'hfScheduleDate.Value'的價值' –

回答

0

這樣做有點「危險」。這裏是幾個選項:

  1. 直接從數據庫中讀取它,而不將其轉換爲字符串第一
  2. 使用DateTime.ParseExact。有關更多詳細信息和示例,請參見MSDN DateTime.ParseExact Method
  3. 對CultureInfo對象使用Convert.ToDateTime。有關更多詳細信息和示例,請參見MSDN How To
0

您必須提供的CultureInfo到皈依這樣

string Date = Convert.ToDateTime("01/02/09", 
         new CultureInfo("en-US")).ToString("yyyy-MMM-dd"); 
         //Results 2009-Jan-02 
string Date = Convert.ToDateTime("01/02/09", 
         new CultureInfo("ru-RU")).ToString("yyyy-MMM-dd"); 
         //Results 2009-Feb-01 
string Date = Convert.ToDateTime("01/02/09", 
         new CultureInfo("ja-JP")).ToString("yyyy-MMM-dd"); 
         //Results 2001-Feb-09 

方法有很多其他的格式,你可以搜索。

0

Convert.ToDateTime方法使用DateTime.Parse方法與您的CurrentCulture設置默認

這意味着(我假設你的05是你的月份部分),您CurrentCulture沒有yyyy/MM/dd HH:mm:ss一個standard date and time format

作爲替代方案,可以使用custom date and time formatting供應確切格式與具有/作爲DateSeparator:TimeSeparatorInvariantCulture(如果您當前的文化沒有這些)

DateTime Date = DateTime.ParseExact(hfScheduleDate.Value, "yyyy/MM/dd HH:mm:ss", 
            CultureInfo.InvariantCulture); 

文化1:由於/ format specifier是自定義日期和時間格式中的日期分隔符,因此默認情況下將使用您的CurrentCultureDateSeparator

相關問題