[英]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.