1

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'

On my development machine, this code works perfectly whereas on my server, its giving me error 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.

I tried adding CultureInfo.InvariantCulture on all four Parse methods, but the error did not go.

Why am I getting this error on server only? How can it be solved?

4

2 回答 2

1

我确定在转换 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()

这不是最好的,但它会完成这项工作。

于 2015-10-21T09:52:50.893 回答
0

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

或者

DateTime.TryParse(dateString,out date4);

如果解析失败,它不会抛出错误,而是返回 false 表示解析失败。

于 2015-10-21T09:34:42.257 回答