0

I use an external API to get some data. Then I do some calculations in Javascript with those data. One field is date in this format: 2015-01-26 18:28:14

Then I have to parse this date. I tried with:

var last = "2015-01-26 18:28:14"
var login = new Date(last).getTime();

But I have an error of Invalid Date. I also tried:

var last = "2015-01-26 18:28:14"
var login = Date.parse(last);
3
  • Works for me in Chrome.
    – j08691
    Commented Jan 26, 2015 at 17:38
  • Gives and error for me unless its in the format "2015/01/26 00:00:00" (firefox)
    – atmd
    Commented Jan 26, 2015 at 17:42
  • ISO-8601 is a well-established and completely interoperable standard. The date parsing logic in some browsers is more tolerant, in some less. (BTW, parse is exactly what new Date uses internally, so don't expect one to work if they other doesn't). There is really no reason for any external API to not return plain vanilla standard date formats. If at all possible, try to get the API changed. Failing that, use a date-parsing library such as moment. The last thing you want to do is spend the rest of your life chasing down some bug in some regexp you wrote to fudge date formats.
    – user663031
    Commented Jan 26, 2015 at 17:54

2 Answers 2

1

You could try insert the character T between the date and the time.

ECMAScript 5 adds support for ISO-8601 dates and times. ISO-8601 stipulates that timestamps with both date and time should be written 2015-01-26T18:28:14.

Note that parse returns:

the number of milliseconds since January 1, 1970, 00:00:00 UTC

See Date.parse() for more info.

2
  • You are right. I didn't think about it since I get the content from API. If I change the format manually, it works :)
    – Tasos
    Commented Jan 26, 2015 at 17:46
  • Yeah, one could argue that the API should use a "standard" format that is easy consumable by programs =P
    – anddoutoi
    Commented Jan 26, 2015 at 17:48
0

Running your code caused errors for me in firefox too

formatting the date like this resolved the issue

"2015/01/26 00:00:00"


var last = "2015/01/26 18:28:14"
var login = new Date(last).getTime();

if you date is coming back with the '-' you can simply do a replace

var d = "2015-01-26 18:28:14";
var login = new Date(d.replace('-', '/')).getTime();

Not the answer you're looking for? Browse other questions tagged or ask your own question.