MomentJs is a helper javascript library that can be used to parse, validate, manipulate, and display dates. I was happily using it in a manner that I thought was appropriate without thinking too much about it until a few days ago, when I realized that the dates displayed in Internet Explorer was different than the date in Chrome! I checked the database and realized that date displayed in Internet Explorer was correct but the date was not in Chrome. The following is a code snippet of how I am using it (in the wrong way). jsfiddle is a great way to test out the following code in both IE and Chrome.
Use the following momentjs script: https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.6.0/moment.min.js.
console.log(moment(new Date('2001-09-08T00:00:00')).format("MM/DD/YYYY"));
The date displayed in IE would be correct - 09/08/2001. The date displayed in Chrome would be wrong - 09/07/2001. It turns out you have to give MomentJs some context when trying to use it to display the appropriate date. Hence, you have to invoke the utc method.
console.log(moment.utc('2001-09-08T00:00:00').format("MM/DD/YYYY"));
This brings an important point - that when you are testing your web application, and you are supporting multiple browsers, it is important to do the same test on all browsers and not assume the same code will work the same across browser platforms. This piece of code will result in a different date being persisted in the database if saved in the browser with the issue.
Comments
Post a Comment