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?
convert.ToDateTime
is actuallyConvert.ToDateTime
, the code never worked. You're callingConvert.ToDateTime(bool)
, which [according to the docs](Calling this method always throws InvalidCastException.) always throws InvalidCastException. Dates are binary values, they have no format. IfdueDate
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 contentsYYYY-MM-DD ...
. Anything else is ambiguous and subject to interpretation. In XML and JSON the ISO8601 is the standard way to represent dates