dougmacklin
dougmacklin

Reputation: 2610

Javascript Invalid Date Error in Internet Explorer

Relatively simple javascript here, not sure why IE hates me (treat others how you want to be treated I suppose).

var newDate = new Date("2012, 11, 2 19:30:00:000");
alert(newDate);

This works in Chrome and FF, but IE outputs "Invalid Date"

Fiddle me this: http://jsfiddle.net/k6yD6/

Upvotes: 46

Views: 87216

Answers (6)

AxelRoss
AxelRoss

Reputation: 1

var time = new Date("2021-12-01 17:02:12");
if(isNaN(time))
{
    time= new Date(date.replace(/ /g,'T')+'.000Z');
}

Upvotes: 0

Prafull
Prafull

Reputation: 591

Use

var newDate = moment("2012, 11, 2 19:30:00:000").toDate();
alert(newDate);

This will work in IE too.

Upvotes: 3

Raghav Manikandan
Raghav Manikandan

Reputation: 679

I was having the same issue with Internet Explorer. This is how I was formatting the date and time initially,

function formatDateTime(date, formatString = 'MM/DD/YYYY hh:mm A') {
  return moment(new Date(date)).format(formatString);
}

The problem was with new Date(). I just removed it as it was already a UTC date. So it is just,

return moment(date).format(formatString);

This worked for me in all browsers including IE.

Upvotes: 3

Sanchi Girotra
Sanchi Girotra

Reputation: 1370

To work in IE, date should be in proper format. I fixed this same issue by using below format:

var tDate = new Date('2011'+"-"+'01'+"-"+'01'); //Year-Month-day

Upvotes: 1

Rich O'Kelly
Rich O'Kelly

Reputation: 41757

The string given to the date constructor should be an RFC2822 or ISO 8601 formatted date. In your example it isn't. Try the following:

new Date("2012-11-02T19:30:00.000Z");

or using an alternate constructor:

new Date(2012, 11, 2, 19, 30, 0)

Upvotes: 64

Korvo
Korvo

Reputation: 9724

IE does not seem to support millisecond and months in Numerical String. Try this:

new Date("November 2, 2012 19:30:00");

or

new Date(year, month, day, hours, minutes, seconds, milliseconds)

Upvotes: 9

Related Questions