Quote of the Day

more Quotes

Categories

Get notified of new posts

Buy me coffee

All posts in ".NET"

Don’t use string when working with dates in javascript/angular and .NET

Published December 10, 2018 in .NET , Angular , Javascript - 3 Comments

Sometimes,  I have seen developers (myself included) use simple strings to represent dates. This could lead to unexpected behaviors if you are not careful. For instance, I recently ran into a bug where the PDF document the program generated show the incorrect date, which was a few hours off from the correct one. The date value originated from a data API and did not include a timezone. The intended time zone was  local time, which is Pacific Standard Time (PST) in this case. However, because we were using storing the date in the angular application using string instead of the javascript built-in Date type, when the framework serialized the data into JSON and sent to .NET, it kept the date as is and did not add any timezone. At the backend, .NET deserialized the value back into a DateTime object, and when we attempted to convert the value to local time usingDateTime.ToLocalTime()for displaying in the document, we got an incorrect value because .NET assumed the date was in Universal Coordinated Time (UTC). 

The bug was because of inconsistencies when passing date values and not including timezone information. However, had we used the frameworks’ built-in types for representing dates instead of strings, we could have avoided the issue. 

Continue reading