Dean Peterson Dean Peterson - 5 months ago 13
Javascript Question

24/August/2016 12:44 AM Not valid in Safari on Mac

I have done quite a bit to make sure the date my date picker creates is compatible for being converted into a javascript Date object. I followed the advice on this stack overflow entry: Invalid date in safari and removed dashes from the string using:
new Date('24-August-2016 12:44 AM'.replace(/-/g, "/")); That made things compatible with every other operating system and browser, except browsers on a Mac. It still seems safari does not like the full month name in the string. What is the recommended approach to getting safari to recognize the string as a date if I am forced to use that format?

som som
Answer

Try formatting with a space instead of a dash or slash - it should work across all modern browsers (including IE and Safari):

var dateString = '24/August/2016 12:44 AM',
    dateFormatted = dateString.replace(/\//g, ' '),
    date = new Date( dateFormatted );

A minor gotcha:

If no timezone if specified in dateString it will default to the user's current timezone. This may not be a problem for your use case, however if someone in Ireland runs the code above they will get a different timestamp to someone in Mexico using the same code.

// defaults to the user's timezone (in my case AEST)
console.log(date); // "Wed Aug 24 2016 00:44:00 GMT+1000 (AEST)"

You can get around this by appending a timezone:

var date = new Date( dateFormatted + ' GMT' );

// timezone is now relative to GMT
console.log(date); // "Wed Aug 24 2016 10:44:00 GMT+1000 (AEST)"
Comments