1

Novice question. I've got a string in the following format:

var dateStr = '2012-4-14';

I want to make it into a JavaScript Date object. The following creates a Date object in Chrome, but is NaN in IE8:

var myDate = new Date(dateStr);

What should I be doing differently - should I split the string?

Thanks!

3 Answers 3

3

Try splitting your date string into year, month, day and instantiating your date differently.

var rawDate = '2012-4-14'.split('-');

var myDate = new Date(rawDate[0], rawDate[1]-1, rawDate[2]);

Note that this will only work if you can guarantee that your date string will be of the same format each time.

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

2 Comments

Don't forget that months are 0 based in JavaScript, so you should subtract 1 from the month if April is desired..
@amnotiam I can't believe I missed that! Considering that this bit me in the *** just the other day.
2

There's a Date.parse in javascript, it recognizes various date formats, see the MDN page for details. For ISO 8601 dates (yours seem to be this one) you can use this library.

This answer also could prove itself useful: Why does Date.parse give incorrect results?

Comments

0

Change var dateStr = '2012-4-14'; to var dateStr = '2012/4/14';

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.