11

I am working with dates in an RSS feed, but am finding differing results when using the code below in IE, Chrome and Firefox:

new Date('2001-01-01T12:00:00Z')

Firefox is happy with that, but Chrome and IE return Invalid Date.

I thought I'd try replacing the T and Z as follows:

new Date('2001-01-01 12:00:00')

This time Chrome is happy with that, but Firefox and IE return Invalid Date.

Any ideas what I should do to get a date object in all browsers with this format?!

Many thanks, Tim

4 Answers 4

24

This works in all browsers on my box - try it in the console:

alert(new Date('2001/01/31 12:00:00'))

so

new Date('2001-01-01T12:00:00Z'.replace(/\-/g,'\/').replace(/[T|Z]/g,' '))

IE8, FF3.6, Safari4, Chrome

Sign up to request clarification or add additional context in comments.

4 Comments

You're right, this works, and it's a better solution than mine.
Many thanks! Tested and working for me in IE, FF, Chrome and Opera!
How do I make this work on FF with timezone? Because this new Date('2001-01-01T12:00:00+1000'.replace(/\-/g,'\/').replace(/[T|Z]/g,' ')) return Invalid date in FF, but works in IE/Chrome
new Date('2001-01-01T12:00:00+1000') works fine in Fx, Chrome
3

You could also try using Date.js - an open source javascript date manipulation library.

1 Comment

Also momentjs (www.momentjs.com) hammers out browser discrepancies.
3

Can you try:

new Date(2001,0,1,12,0,0)

This means:

new Date(year,month,day,hour,minutes,seconds) 

2 Comments

You mean new Date(2001,0,1,12,0,0) since JS months start with 0
Be careful with leading 0s. 08 and 09 are invalid octal numbers
3

This works on all of the major 5 browsers and causes all browsers to recognize the time as GMT/UTC rather than local time (the Z suffix means the time is UTC):

new Date('2001-01-01T12:00:00Z'.replace(/\-/g,'\/').replace(/T/,' ').replace(/Z/,' -0'))

I thank mplungjan for his answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.