[英]String was not recognized as a valid DateTime server error
Below is my code 下面是我的代码
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()
The value of SV.FieldName = '19-06-2015'
, StartDate = '2015-09-20T00:00:00Z'
, EndDate = '2015-10-21T23:59:59Z'
SV.FieldName = '19-06-2015'
的值SV.FieldName = '19-06-2015'
, StartDate = '2015-09-20T00:00:00Z'
, EndDate = '2015-10-21T23:59:59Z'
On my development machine, this code works perfectly whereas on my server, its giving me error String was not recognized as a valid DateTime
在我的开发机器上,此代码可以完美运行,而在我的服务器上,它给我的错误
String was not recognized as a valid DateTime
Both my machines have date format set as English(India), Location as India and Timezone set as UTC. 我的两台机器都将日期格式设置为英语(印度),将位置设置为印度,并将时区设置为UTC。
I tried adding CultureInfo.InvariantCulture
on all four Parse methods, but the error did not go. 我尝试在所有四个Parse方法上添加
CultureInfo.InvariantCulture
,但是错误没有消失。
Why am I getting this error on server only? 为什么我仅在服务器上收到此错误? How can it be solved?
如何解决?
I'm certain that the error comes when converting the value of s.FieldName = '19-06-2015'. 我确定转换s.FieldName = '19 -06-2015'的值时会出现错误。 The compiler assume that the format is MM-dd-yyyy and therefor 19 is seen as an invalid month number.
编译器假定格式为MM-dd-yyyy,因此19被视为无效的月份号。
my suggestion will be to construct the date value, see below 我的建议是构造日期值,请参见下文
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()
this is not the best but it will do the job. 这不是最好的方法,但可以完成任务。
Try using DateTime.ParseExact(dateString, @"d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture); 尝试使用DateTime.ParseExact(dateString,@“ d / M / yyyy”,System.Globalization.CultureInfo.InvariantCulture);
or 要么
DateTime.TryParse(dateString,out date4); DateTime.TryParse(dateString,out date4);
if the parsing fails, it will not throw error, rather it returns false indicating that the parsing failed. 如果解析失败,则不会引发错误,而是返回false表示解析失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.