Incorrect date shown in new Date() in JavaScript

前端 未结 3 378
不思量自难忘°
不思量自难忘° 2020-11-28 14:55

This is what I get in chrome console. I pass \"2016-09-05\"(YYYY-MM-DD) as the date and it shows me Sept 4,2016 as the date.

Another constructor shows the

相关标签:
3条回答
  • 2020-11-28 15:03

    If you omit the time in the new Date(string) constructor, UTC time is assumed. So the displayed value is actually correct. Use new Date('2016-09-05 00:00') to create the date object in local time.

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

    use setFullYear the syntax is Date.setFullYear(year,month,day)

    mydate = new Date();
    mydate.setFullYear(2016, 08, 05);
    
    0 讨论(0)
  • 2020-11-28 15:21

    You could use the Solution from UTC Date Conversion. Which basicall does the following:

    console.log(new Date("2014-12-23"));
    console.log(convertDateToUTC(new Date("2014-12-23")));
    
    function convertDateToUTC(date) { 
    return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()); 
    }
    

    The output would be like that in the console (for me at least :D)

    Tue Dec 23 2014 01:00:00 GMT+0100 (Mitteleuropäische Zeit)
    Tue Dec 23 2014 00:00:00 GMT+0100 (Mitteleuropäische Zeit)

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