46

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/

dougmacklin
  • 2,560
  • 10
  • 42
  • 69
  • 1
    I actually get invalid date in Firefox as well (latest version, 16.0.1). – Ashley Strout Oct 26 '12 at 17:23
  • 3
    Just make sure you're using a properly supported format. This question has been asked plenty of times before, http://stackoverflow.com/questions/3020508/ie-javascript-date-parsing-error – Christian Oct 26 '12 at 17:24
  • 1
    for IE its dateObj = new Date(year, month, date[, hours[, minutes[, seconds[,ms]]]]) – Amitd Oct 26 '12 at 17:25
  • 7
    Don't worry. IE hates everyone – Kellen Stuart Dec 22 '17 at 02:55
  • 2
    Or Microsoft could just BE NICE like other browsers! .. Terrible browser – sean2078 Mar 08 '18 at 02:37
  • https://www.csgpro.com/blog/2016/08/a-bad-date-with-internet-explorer-11-trouble-with-new-unicode-characters-in-javascript-date-strings . This post will be helpful for someone :) – Rigin Jun 04 '18 at 05:37

6 Answers6

64

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)
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
9

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)
Protomen
  • 9,471
  • 9
  • 57
  • 124
3

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.

3

Use

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

This will work in IE too.

Prafull
  • 591
  • 6
  • 16
1

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
HadiRj
  • 1,015
  • 3
  • 21
  • 41
Sanchi Girotra
  • 1,232
  • 13
  • 13
  • 1
    When I passed this year-month-day format into my code, it fixed the problem... gotta give you a 1 up. However, I didn't need the new Date, just change the format as a string and the date appeared correctly on the server side via IE 11. – Clarence Apr 07 '17 at 22:52
0
var time = new Date("2021-12-01 17:02:12");
if(isNaN(time))
{
    time= new Date(date.replace(/ /g,'T')+'.000Z');
}
Esdras Xavier
  • 867
  • 1
  • 7
  • 18