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?
I'm certain that the error comes when converting the value of 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.
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);
or
DateTime.TryParse(dateString,out date4);
if the parsing fails, it will not throw error, rather it returns false indicating that the parsing failed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.