Monday, 7 January 2019

Date Format Compatiblity Cross Browser

Solution 1
Using a format date from momment js (plugin)
moment().format('MMMM Do YYYY, h:mm:ss a'); // January 7th 2019, 2:48:53 pm
moment().format('dddd');                    // Monday
moment().format("MMM Do YY");               // Jan 7th 19
moment().format('YYYY [escaped] YYYY');     // 2019 escaped 2019
moment().format();                          // 2019-01-07T14:48:53+08:00
The Solution
The problem lies in the format that you pass the required date to the Date() object. For some reason, and don’t ask me why, the two aforementioned browsers surprisingly do not support the date format “yyyy-mm-dd” and therefore fail. I haven’t managed to compile a definitive list of supported date formats, however I can tell you the following formats are definitely supported across all browsers and would advise sticking to one of these to avoid errors:


  1. var d = new Date(2011, 01, 07); // yyyy, mm-1, dd  
  2. var d = new Date(2011, 01, 07, 11, 05, 00); // yyyy, mm-1, dd, hh, mm, ss  
  3. var d = new Date("02/07/2011"); // "mm/dd/yyyy"  
  4. var d = new Date("02/07/2011 11:05:00"); // "mm/dd/yyyy hh:mm:ss"  
  5. var d = new Date(1297076700000); // milliseconds  
  6. var d = new Date("Mon Feb 07 2011 11:05:00 GMT"); // ""Day Mon dd yyyy hh:mm:ss GMT/UTC  
Reference
http://biostall.com/javascript-new-date-returning-nan-in-ie-or-invalid-date-in-safari/
https://momentjs.com/

No comments:

Post a Comment