Why is this Javascript not working in Firefox?

I am trying to manipulate a date using 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 convert

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

It works fine in Chrome, you can test the code through Fiddle . He always returns

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

For three console.logsin 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.

+4
source share
3 answers

The format of your date should be “RFC 2822 time stamp compatible with IETF”, and there is incorrect cross-browser if it is not.

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

- '-' '/',

+5

YYYY-MM-DD HH:MM:SS:

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

v , ,

( , , Date.parse(...))

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

, (15.9.1.15). String , , , . , String, Date.parse NaN.

: http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15

: YYYY-MM-DDTHH: mm: ss.sssZ

, - , YYYY-MM-DD HH:MM:SS.

:

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);
+2

Firefox:

new Date("2013-07-23 12:00:00").toString()   // Invalid
new Date("2013-07-23T12:00:00").toString()   // Local noon
new Date("2013-07-23T12:00:00Z").toString()  // UTC noon
new Date("2013/07/23 12:00:00").toString()   // Local noon

Chrome:

new Date("2013-07-23 12:00:00").toString()   // Local noon
new Date("2013-07-23T12:00:00").toString()   // UTC noon
new Date("2013-07-23T12:00:00Z").toString()  // UTC noon
new Date("2013/07/23 12:00:00").toString()   // Local noon

. , Chrome :

new Date("2013-07-23 00:00:00").toString()   // Local midnight
new Date("2013-07-23").toString()            // UTC midnight

If you need to parse dates from strings sequentially, you should use a library like moment.js .

moment("2013-07-23 12:00:00", "YYYY-MM-DD HH:mm:ss").format()     // Local noon
moment.utc("2013-07-23 12:00:00", "YYYY-MM-DD HH:mm:ss").format() // UTC noon

The main advantage is that you can control the input and output formats, and it works the same in all browsers.

0
source

All Articles