henrywright
henrywright

Reputation: 10240

Is there a way to create a JavaScript date instance from an ISO 8601 date which works in all browsers?

When I try to create a JavaScript date instance from an ISO 8601 date using FireFox (and IE) I get "Invalid Date":

var d = new Date('2015-05-05Z');
alert(d); // Invalid Date

But things work OK in Chrome:

var d = new Date('2015-05-05Z');
alert(d); // Tue May 05 2015 01:00:00 GMT +0100 (BST)

Demo: https://jsfiddle.net/z50LL4he/

Is there a way to create a JavaScript date instance from an ISO 8601 date that works in FireFox? Please note, I'm trying to do this without using a library such as momentjs.

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Upvotes: 1

Views: 99

Answers (3)

kennebec
kennebec

Reputation: 104760

If you expect date strings to have the form you present, you can convert them to ISO by adding the time (midnight GMT).

If you pass an actual ISO string (or any other correctly formatted date string) it will make a date without changing anything.

It will return 'Invalid Date' for invalid strings.

function almostISO(s){
    return new Date(s.replace(/(\d{4}\-\d\d\-\d\d)Z/, '$1T00:00:00Z'));
}

var d= '2015-05-05Z';

almostISO(d).toUTCString();

returned value: (String)>> Tue, 05 May 2015 00:00:00 GMT

Upvotes: 2

Mike Hamilton
Mike Hamilton

Reputation: 1567

The "Z" at the end of your date string is a time zone designator. Because you aren't providing a time but a date and a timezone, it is causing the error in some browsers - this is not a valid ISO 8601 date.

Since it seems the Chrome/Safari will actually return a usable date and Firefox/IE doesn't, we can at least setup some error handling to detect if the date was output correctly and handle accordingly.

In FireFox, if we pass the invalid date string into the isNaN() function, it returns true. Knowing that we can say something like:

if(isNaN(date)){
    //handle the error appropriately
}
else{
    //carry on like nothing happened
}

Upvotes: 5

Downgoat
Downgoat

Reputation: 14361

My browser (Safari) and possible others don't seem to like the Z at the end, it designates the Timezone instead of the actual time. You can trim it off (Trims all letters from the end of the string):

var dateString = '2015-05-05Z'.replace(/[A-Za-z]+$/, ''),
    date       = new Date(dateString);

Upvotes: 3

Related Questions