简体   繁体   English

日期时间解析错误

[英]date time parse error

I'm using .net Framework 4.0 and developing an console app. 我正在使用.net Framework 4.0并开发一个控制台应用程序。

My regional setting are set as en-us. 我的区域设置设置为en-us。

I'm getting error: 我收到错误:

String was not recognized as a valid DateTime. 字符串未被识别为有效的DateTime。

on following code. 在下面的代码。

DateTime time = XmlConvert.ToDateTime("2013-11-08T08:08:32+5.5", "yyyy-M-dTH:m:sz");

I'm testing my app in windows 2008 R2 server. 我在Windows 2008 R2服务器上测试我的应用程序。

Your code does not account for the .5 bit ( z takes care just of the +5 part without decimals). 你的代码没有考虑.5位( z只关注+5部分没有小数)。 Corrected version: 更正版本:

DateTime time = XmlConvert.ToDateTime("2013-11-08T08:08:32+5.5", "yyyy-M-dTH:m:sz.f");

UPDATE UPDATE

As rightly pointed out by digEmAll via comments, the proposed .f correction avoids the problem although does not account for the date properly. 正如digEmAll通过评论正确指出的那样,建议的.f修正避免了这个问题,尽管没有正确地考虑日期。 The .f modifier refers always to a fraction of second, even in case of being located far away from seconds (as in this case). .f修饰符总是指一小部分秒,即使位于远离秒的位置(如本例所示)。 The fractions of z have to be provided by relying on the : modifier and by converting z into zzz . 必须通过依赖于:修饰符和将z转换为zzz来提供z的分数。

Thus, the aforementioned code represents a practical solution for the OP's conditions (technically speaking, taking a wrong date format as inputs), although does not deliver an accurate result. 因此,上述代码代表了OP条件的实际解决方案(从技术上讲,将错误的日期格式作为输入),尽管不能提供准确的结果。 A pre-modification of the input format would be required in order to accomplish so, that is: 为了实现这一目的,需要对输入格式进行预修改,即:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM