0

I recently ran into an issue with the following line of code Linq:

var directions = unitDirections.Directions
.Where(d => Convert.ToDateTime(d.DueDate) > DateTime.Today || (Convert.ToDateTime(d.DueDate) <= DateTime.Today && d.DirStatus == "OPN")).ToList();

It all worked fine running local. But once published to Azure the code broke and had to be fixed with DateParse and Invariant Culture. This is due to the target OS being Linux. This is the code that fixed it:

unitDirections.Directions.Where(d => Convert.ToDateTime(DateTime.ParseExact(d.DueDate, "dd/MM/yyyy", CultureInfo.InvariantCulture)) > DateTime.Today ||           (Convert.ToDateTime(DateTime.ParseExact(d.DueDate, "dd/MM/yyyy", CultureInfo.InvariantCulture)) <= DateTime.Today && d.DirStatus == "OPN")).ToList();

Here's a related post: DateTime Parse Exact. Not working on Azure

How do I avoid this and guard against it in the future? Beyond trying to remember, is there a way to remind me when I build the project in Visual Studio? Is there any warning that could be set?

10
  • 2
    Maybe you should try explicitly setting the culture. This might help: stackoverflow.com/questions/13354211/… Commented Jul 4 at 8:24
  • 2
    What you linked to is unrelated, and if convert.ToDateTime is actually Convert.ToDateTime, the code never worked. You're calling Convert.ToDateTime(bool), which [according to the docs](Calling this method always throws InvalidCastException.) always throws InvalidCastException. Dates are binary values, they have no format. If dueDate is a real date, there's no need to parse it or convert it to anything. If it's a string, you have a critical bug. Change it to a proper Date type like DateTime or DateOnly instead of trying to guess string contents Commented Jul 4 at 8:29
  • 2
    The real solution is always to use proper date types. If there's no way to do that, eg in SQLite which has no data types, use the ISO8601 format only, ie YYYY-MM-DD .... Anything else is ambiguous and subject to interpretation. In XML and JSON the ISO8601 is the standard way to represent dates Commented Jul 4 at 8:33
  • Sorry for the lack of clarity. I updated the code sections to demonstrate. The question is. How do I avoid making this mistake again? I can try setting the culture to "invariant" for the thread. Commented Jul 4 at 10:12
  • @PanagiotisKanavos I've added in the exact code. Sorry for the confusion. Commented Jul 4 at 10:13

0

Browse other questions tagged or ask your own question.