Why converting new.Date() .toISOString() changes the time?

前端 未结 3 1830
-上瘾入骨i
-上瘾入骨i 2021-02-19 00:04

I\'m inserting a date in a database in two different format.

this is inserting as Datetime

    var mydate;
    mydate = new Date();
            


        
3条回答
  •  无人及你
    2021-02-19 00:11

    In your this is inserting as Datetime block your slice are stripping of the timezone part (the Z at the end of toISOString output):

    document.getElementById('clockinhour').value = mydate.toISOString().slice(0, 19).replace('T', ' ');
    

    As pointed out by @RobG in the comments section, toISOString should always return the date in UTC (Z or +00:00).

    RTFM: "The time zone [offset] is always UTC, denoted by the suffix Z",

    The time "changes" because it is converted to UTC when you calls toISOString.

    If you want to get ISO date in your timezone, you should take a look in these two questions: How to ISO 8601 format a Date with Timezone Offset in JavaScript? and How to format a JavaScript date

提交回复
热议问题