簡體   English   中英

DateTime.ParseExact賦予String未被識別為有效的DateTime。

[英]DateTime.ParseExact gives String was not recognized as a valid DateTime.

我正在嘗試將日期字符串解析為DateTime變量。 我發現ParseExact是這樣做的方法,但我試試這個我得到錯誤:

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

string timeFormat = "dd-MM-yyyy hh:mm:ss";
DateTime startDate = DateTime.ParseExact(reader["startdate"].ToString(), timeFormat, CultureInfo.InvariantCulture);
DateTime nextDate = DateTime.ParseExact(reader["nextdate"].ToString(), timeFormat, null);

我已嘗試使用null (恰好在另一頁上工作)和CultureInfo.InvariantCulture

reader["startdate"].ToString()輸出:01-08-2012 15:39:09

reader["nextdate"].ToString()輸出:01-08-2012 15:39:09

我認為它應該有效,但事實並非如此。

有人知道出了什么問題? :)

你在格式字符串中使用hh 這是一個12小時的“一天一小時”字段。 值15不在范圍內......

你想要HH ,這是24小時的說明符。

有關詳細信息,請參閱MSDN自定義日期和時間格式字符串文檔

很可能是由於您的服務器區域設置和UI區域設置之間的差異

一種更簡單的方法是在web.config中指定全球化詳細信息

喜歡

<configuration>
   <system.web>
      <globalization culture="en-GB"/>
   </system.web>
</configuration>

或者更詳細

<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="en-GB" uiCulture="en-GB" />

但請確保這不會與您的應用程序發生沖突

試試這個有效

DateTime.ParseExact("01-08-2012 15:36:25", "dd-MM-yyyy HH:mm:ss", null);

我不確定這是否有幫助但是我使用了本文中的確切代碼並且它對我有用,因為DateTime.ParseExact(dat,“dd / MM / yyy HH:MM”,CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles。沒有)對我不起作用。

閱讀本文我剛剛在網上發布: http//rochcass.wordpress.com/2012/08/27/error-string-was-not-recognized-as-a-valid-datetime-solution/#more-350

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM