Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this Javascript not work in Firefox?

I am trying to manipulate a date with some simple Javascript. The code is as follows:

var newDate = new Date("2013-07-23" + " 12:00:00");
console.log(newDate.toString());
newDate = new Date(newDate.getTime() - (24 * 60 * 60 * 1000));
console.log(newDate.toString());
var date = newDate.getFullYear() + "-" + ("0" + (newDate.getMonth() + 1)).slice(-2) + "-" + ("0" + newDate.getDate()).slice(-2);
console.log(date);

Essentially, I am converting

2013-07-23 -> Jul 22 2013 12:00:00 GMT+1000 -> 2013-07-22

It works fine in Chrome, you can test the code via this Fiddle. It always returns

"Invalid Date"
"Invalid Date"
"NaN-aN-aN"

For the three console.logs in Firefox, but:

Tue Jul 23 2013 12:00:00 GMT+1000 (E. Australia Standard Time)
Mon Jul 22 2013 12:00:00 GMT+1000 (E. Australia Standard Time) 
2013-07-22

For Chrome.

like image 912
JosephGarrone Avatar asked Mar 22 '23 06:03

JosephGarrone


2 Answers

Your date format should be "IETF-compliant RFC 2822 timestamp" and there's some cross-browser inconsistency if it's not.

Read about it here: http://dygraphs.com/date-formats.html

But basically - you should just replace '-' with '/' to make it work on any existing browser

like image 56
Adassko Avatar answered Mar 24 '23 19:03

Adassko


The spec does not require that the date format YYYY-MM-DD HH:MM:SS be parsed:

new Date: http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.3.2

Parse v as a date, in exactly the same manner as for the parse method

(essentially, the same result as Date.parse(...))

Date.parse: http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.4.2

The function first attempts to parse the format of the String according to the rules called out in Date Time String Format (15.9.1.15). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats. Unrecognisable Strings or dates containing illegal element values in the format String shall cause Date.parse to return NaN.

Date Time String Format: http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15

The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ

There is no guarantee that any other format works, including YYYY-MM-DD HH:MM:SS.

You can always construct a conformant date string:

var newDate = new Date("2013-07-23" + "T12:00:00.000Z");
console.log(newDate.toString());
newDate = new Date(newDate.getTime() - (24 * 60 * 60 * 1000));
console.log(newDate.toString());
var date = newDate.getFullYear() + "-" + ("0" + (newDate.getMonth() + 1)).slice(-2) + "-" + ("0" + newDate.getDate()).slice(-2);
console.log(date);
like image 33
SheetJS Avatar answered Mar 24 '23 20:03

SheetJS