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

前端 未结 23 1109
爱一瞬间的悲伤
爱一瞬间的悲伤 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:18

    This code will return your Date object formatted with the browser timezone.

    Date.prototype.timezone = function () {
        this.setHours(this.getHours() + (new Date().getTimezoneOffset() / 60));
        return this;
    }
    

    Edit:

    To avoid to pollute the Date API, the above function can be transformed into a utility function. The function takes a Date object, and returns a mutated Date object.

    function setTimeZone(date) {
        date.setHours(date.getHours() + (new Date().getTimezoneOffset() / 60));
        return date;
    }
    
    0 讨论(0)
  • 2020-11-22 02:18

    I used the timezone-js package.

    var timezoneJS  = require('timezone-js');
    var tzdata = require('tzdata');
    
    createDate(dateObj) {
        if ( dateObj == null ) {
            return null;
        }
        var nativeTimezoneOffset = new Date().getTimezoneOffset();
        var offset = this.getTimeZoneOffset();
    
        // use the native Date object if the timezone matches
        if ( offset == -1 * nativeTimezoneOffset ) {
            return dateObj;
        }
    
        this.loadTimeZones();
    
        // FIXME: it would be better if timezoneJS.Date was an instanceof of Date
        //        tried jquery $.extend
        //        added hack to Fiterpickr to look for Dater.getTime instead of "d instanceof Date"
        return new timezoneJS.Date(dateObj,this.getTimeZoneName());
    },
    
    0 讨论(0)
  • 2020-11-22 02:19

    any mileage in

    var d = new Date(xiYear, xiMonth, xiDate).toLocaleString();
    
    0 讨论(0)
  • 2020-11-22 02:19

    This worked for me. Not sure if it is a good idea though.

    var myDate = new Date();
    console.log('myDate:', myDate);   // myDate: "2018-04-04T01:09:38.112Z"
    
    var offset = '+5';  // e.g. if the timeZone is -5
    
    var MyDateWithOffset = new Date( myDate.toGMTString() + offset );   
    
    console.log('MyDateWithOffset:', MyDateWithOffset); // myDateWithOffset: "2018-04-03T20:09:38.000Z"

    0 讨论(0)
  • 2020-11-22 02:22

    I know this is old but if it helps you could use moment and moment time zone. If you haven't seen them take a look.

    http://momentjs.com/timezone/

    http://momentjs.com/

    two really handy time manipulation libraries.

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