String was not recognized as a valid DateTime in c#?

I am write this code for date range filter in c# using linq.but getting like this error on server.in my local code working very well but deploy on server getting error.

here i have try this code:

string fromDate = "15-03-2017";
string toDate = "17-03-2017";
DateTime FromDate = Convert.ToDateTime(fromDate);
DateTime ToDate = Convert.ToDateTime(toDate);                        
UserList = db.Users
     .Where(t => DbFunctions.TruncateTime(t.datetime) >= FromDate && DbFunctions.TruncateTime(t.datetime) <= ToDate)
     .OrderByDescending(a => a.datetime)
     .ToList();

i don't know where is my mistke in this query any one know then please let me know how o resolve this issue.in local code working very well but on server getting error.

Jon Skeet
people
quotationmark

You're using a method that depends on the current thread's current culture - and the system time zone.

You'd be much better off using DateTime.ParseExact in my view, and potentially specifying a DateTimeStyles value to force the use of UTC. Simple parsing:

// Names changed to follow .NET naming conventions
CultureInfo invariantCulture = CultureInfo.InvariantCulture;
DateTime fromDateTime = DateTime.ParseExact(fromDate, "dd-MM-yyyy", invariantCulture);
DateTime toDateTime = DateTime.ParseExact(toDate, "dd-MM-yyyy", invariantCulture);

Specifying the invariant culture means that you won't accidentally end up parsing the date as if it's specified in a non-Gregorian calendar.

Note that this is an unusual format to start with - if you can use an ISO-8601 format, that would be better IMO.

I'd also suggest that if you're doing significant amounts of date/time work, you consider my Noda Time project, which makes life simpler in terms of not worrying about the time zone of a date, because it's just a date... you'd parse these strings as LocalDate values.

people

See more on this question at Stackoverflow