[英]date time parse error
我正在使用.net Framework 4.0並開發一個控制台應用程序。
我的區域設置設置為en-us。
我收到錯誤:
字符串未被識別為有效的DateTime。
在下面的代碼。
DateTime time = XmlConvert.ToDateTime("2013-11-08T08:08:32+5.5", "yyyy-M-dTH:m:sz");
我在Windows 2008 R2服務器上測試我的應用程序。
你的代碼沒有考慮.5
位( z
只關注+5
部分沒有小數)。 更正版本:
DateTime time = XmlConvert.ToDateTime("2013-11-08T08:08:32+5.5", "yyyy-M-dTH:m:sz.f");
UPDATE
正如digEmAll通過評論正確指出的那樣,建議的.f
修正避免了這個問題,盡管沒有正確地考慮日期。 .f
修飾符總是指一小部分秒,即使位於遠離秒的位置(如本例所示)。 必須通過依賴於:
修飾符和將z
轉換為zzz
來提供z
的分數。
因此,上述代碼代表了OP條件的實際解決方案(從技術上講,將錯誤的日期格式作為輸入),盡管不能提供准確的結果。 為了實現這一目的,需要對輸入格式進行預修改,即:
string input = "2013-11-08T08:08:32+5.5";
string format = "yyyy-M-dTH:m:sz";
string correctedInput = input;
string correctedFormat = format;
string[] temp = input.Split('.');
if (temp.Length == 2 && temp[1].AsEnumerable().Select(x => char.IsDigit(x)).Count() == temp[1].Length)
{
correctedInput = temp[0] + ":" + Convert.ToString(Math.Round(60 * Convert.ToDecimal(temp[1]) / 10, 2));
correctedFormat = "yyyy-M-dTH:m:szzz";
}
DateTime time = XmlConvert.ToDateTime(correctedInput, correctedFormat);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.