Create a Date with a set timezone without using a string representation

前端 未结 23 1484
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 01:48

I have a web page with three dropdowns for day, month and year. If I use the JavaScript Date constructor that takes numbers, then I get a Date obje

23条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 02:15

    I was having a similar problem with a date picker. My research led to a very simple solution, without any extra libraries or hardcoded multipliers.

    Key info:

    1. ISO is the Javascript preferred date standard. Assume date utilities will likely return date values in that format.
      • My date picker displays the date in a localized format: mm/dd/yyyy

      • However, it returns the date value in the ISO format: yyyy-mm-dd

        //Select "08/12/2020" in Date Picker date_input 
        
        var input = $('#date_input').val();  //input: 2020-08-12
        
    1. Date.getTimezoneOffset() returns the offset in minutes.

    Examples:

    If you use the default returned date value without modifying the string format, the Date might not get set to your timezone. This can lead to unexpected results.

    var input = $('#date_input').val();  //input: 2020-08-12
    var date = new Date(input);          //This get interpreted as an ISO date, already in UTC
    //date:                             Tue Aug 11 2020 20:00:00 GMT-0400 (Eastern Daylight Time)
    //date.toUTCString():               Wed, 12 Aug 2020 00:00:00 GMT
    //date.toLocaleDateString('en-US'):       8/11/2020
    

    Using a different date string format than the ISO standard yyyy-mm-dd applies your timezone to the Date.

    var date = new Date("08/12/2020");  //This gets interpreted as local timezone
    //date:                             Wed Aug 12 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
    //date.toUTCString():               Wed, 12 Aug 2020 04:00:00 GMT
    //date.toLocaleDateString('en-US'):       8/12/2020
    

    Solution:

    To apply your timezone to the format-agnostic Date without doing string manipulation, use Date.getTimezoneOffset() with Minutes. This works with either original date string format (i.e. UTC dates or localized dates). It provides a consistent result which can then be converted accurately to UTC for storage or interacting with other code.

    var input = $('#date_input').val();
    var date = new Date(input);
    date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
    //date:                             Wed Aug 12 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
    //date.toUTCString():               Wed, 12 Aug 2020 04:00:00 GMT
    //date.toLocaleDateString('en-US'):       8/12/2020
                    
    

提交回复
热议问题