繁体   English   中英

无法将字符串识别为有效的DateTime服务器错误

[英]String was not recognized as a valid DateTime server error

下面是我的代码

var result =
    (from SV in Tbl
     where (DateTimeOffset.Parse(SV.FieldName) >= DateTimeOffset.Parse(StartDate) 
     && DateTimeOffset.Parse(SV.FieldName) <= DateTimeOffset.Parse(EndDate))
     group SV by 1 into SVgrp
     select new { Count = SVgrp.Sum(p => p.Count) }).ToList()

SV.FieldName = '19-06-2015'的值SV.FieldName = '19-06-2015'StartDate = '2015-09-20T00:00:00Z'EndDate = '2015-10-21T23:59:59Z'

在我的开发机器上,此代码可以完美运行,而在我的服务器上,它给我的错误String was not recognized as a valid DateTime

我的两台机器都将日期格式设置为英语(印度),将位置设置为印度,并将时区设置为UTC。

我尝试在所有四个Parse方法上添加CultureInfo.InvariantCulture ,但是错误没有消失。

为什么我仅在服务器上收到此错误? 如何解决?

我确定转换s.FieldName = '19 -06-2015'的值时会出现错误。 编译器假定格式为MM-dd-yyyy,因此19被视为无效的月份号。

我的建议是构造日期值,请参见下文

    var result = (from SV in Tbl
           where (new DateTime(Convert.ToInt32(SV.FieldName.Substring(6, 4)), Convert.ToInt32(SV.FieldName.Substring(3, 2)), Convert.ToInt32(SV.FieldName.Substring(0, 2))) >= DateTimeOffset.Parse(StartDate) 
           && new DateTime(Convert.ToInt32(SV.FieldName.Substring(6, 4)), Convert.ToInt32(SV.FieldName.Substring(3, 2)), Convert.ToInt32(SV.FieldName.Substring(0, 2))) <= DateTimeOffset.Parse(EndDate))
           group SV by 1 into SVgrp
           select new { Count = SVgrp.Sum(p => p.Count) }).ToList()

这不是最好的方法,但可以完成任务。

尝试使用DateTime.ParseExact(dateString,@“ d / M / yyyy”,System.Globalization.CultureInfo.InvariantCulture);

要么

DateTime.TryParse(dateString,out date4);

如果解析失败,则不会引发错误,而是返回false表示解析失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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