new Date() is working in Chrome but not Firefox

I am creating a datetime string that looks like this: 2010-07-15 11:54:21

And with the following code I get invalid date in Firefox but works just fine in Chrome

var todayDateTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + seconds;
var date1 = new Date(todayDateTime);

In firefox date1 is giving me an invalid date, but in chrome its working just fine what would the main cause be?


You can't instantiate a date object any way you want. It has to be in a specific way. Here are some valid examples:

new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)

or

d1 = new Date("October 13, 1975 11:13:00")
d2 = new Date(79,5,24)
d3 = new Date(79,5,24,11,33,0)

Chrome must just be more flexible.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

From apsillers comment:

the EMCAScript specification requires exactly one date format (i.e., YYYY-MM-DDTHH:mm:ss.sssZ) but custom date formats may be freely supported by an implementation: "If the String does not conform to that [ECMAScript-defined] format the function may fall back to any implementation-specific heuristics or implementation-specific date formats." Chrome and FF simply have different "implementation-specific date formats."


This works in all browsers -

new Date('2001/01/31 12:00:00 AM')

new Date('2001-01-31 12:00:00')

Format: YYYY-MM-DDTHH:mm:ss.sss

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


Option 1 :

Suppose your timestring has a format that looks like this :

'2016-03-10 16:00:00.0'

In that case, you could do a simple regex to convert it to ISO 8601 :

'2016-03-10 16:00:00.0'.replace(/ /g,'T')

This would procude the following output :

'2016-03-10T16:00:00.0'

This is the standard datetime format, and thus supported by all browsers :

document.body.innerHTML = new Date('2016-03-10T16:00:00.0') // THIS IS SAFE TO USE

Option 2 :

Suppose your timestring has a format that looks like this :

'02-24-2015 09:22:21 PM'

Here, you can do the following regex :

'02-24-2015 09:22:21 PM'.replace(/-/g,'/');

This, too, produces a format supported by all browsers :

document.body.innerHTML = new Date('02/24/2015 09:22:21 PM') // THIS IS SAFE TO USE

Option 3 :

Suppose you have a time string that isn't easy to adjust to one of the well-supported standards.

In that case, it's best to just split your time string into different pieces and use them as individual parameters for Date :

document.body.innerHTML = new Date(2016, 2, 26, 3, 24, 0); // THIS IS SAFE TO USE

This works in most browsers as well

new Date('2001/01/31 12:00:00')

That is the format of

"yyyy/MM/dd HH:mm:ss"