Javascript Invalid Date Error in Internet Explorer

后端 未结 5 1761
野趣味
野趣味 2020-11-28 11:27

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:0         


        
相关标签:
5条回答
  • 2020-11-28 12:06

    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)
    
    0 讨论(0)
  • 2020-11-28 12:12

    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.

    0 讨论(0)
  • 2020-11-28 12:15

    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
    
    0 讨论(0)
  • 2020-11-28 12:26

    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)
    
    0 讨论(0)
  • 2020-11-28 12:26

    Use

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

    This will work in IE too.

    0 讨论(0)
提交回复
热议问题