0

I'm receiving this date/time from an API:

2012-03-31 12:00:00

What is the best way to do this:

var date = new Date("2012-03-31 12:00:00") without Firefox complaining of an Invalid Date?

4
  • 1
    Use a library like momentjs.com ? Commented Feb 25, 2013 at 11:11
  • @FelixKling Really?? Is the use of a library needed to do this? Commented Feb 25, 2013 at 11:12
  • No it's not needed, you can also parse the string yourself and extract the fields and pass them to Date. Commented Feb 25, 2013 at 11:13
  • @FelixKling Yeah, so at the moment, I'm doing: val = val.replace(/-/ig, ','); just seems a little hacky. Commented Feb 25, 2013 at 11:14

2 Answers 2

3

You can match all the fields in the date time string with:

var str = "2012-03-31 12:00:00";
var fields = str.match(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/);

Now fields[1] contains the year, fields[2] the month, etc. Then you can call Date with:

// months are zero-based, so we have to subtract 1
var date = new Date(+fields[1], +fields[2] - 1, +fields[3], +fields[4], +fields[5], +fields[6]);

Or use a library like http://momentjs.com/ which does this for you.

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

1 Comment

Nice answer, if your date string has in a different format just modify the regex groups and works.
2

If you just want the date you could use:

var date = new Date("2012-03-31 12:00:00".split(" ")[0]);

& firefox wont complain.

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.