简体   繁体   中英

Convert a JavaScript Date object to a different timezone

I have a JavaScript Date object that is manually set by the user. The problem is that when the date is created on the client, the Date constructor builds the date object according to the clients timezone.

For example, I live in the CST timezone, but if I set my PC to EST time, then the Date constructor will construct a different date object.

The question is:

How can I convert a date object to a certain timezone? Eg a clients machine is EST time and I need to convert the date object to CST time.

Update

Here is my JS as of now

// returns local time in msecs given a UTC offset
Date.prototype.getLocalTime = function(offset) {
    var MSEC_HOUR = 3600000; // milliseconds in an hour
    var MSEC_MIN = 60000; // milliseconds in a minute

    // convert client sides local time
    var utc = this.getTime() + (this.getTimezoneOffset() * MSEC_MIN);
    return utc + (offset * MSEC_HOUR);
};

var offset = -6.0; // Central Standard Time UTC offset  
var date = form.getDate(); // get user date input   
var msecs = date.getLocalTime(offset);

// converted clients form date input to CST
var convertedDate = new Date(msecs);

Timezone is always a tricky thing. You can either use getUTCHours() , which returns the universal time, and go from there or you can use something like momentjs.

If you want to use a certain timezone, you may want to settle on UTC, seeing how it is made for this purpose, rather than any other timezones

Date.UTC(year, month[, day[, hour[, minute[, second[, millisecond]]]]])

will return a number of miliseconds since UTC's start, which can then be piped into

var date = new Date(Date.UTC(year, month, day, hour, min);

This can be done using moment.js

ConvertDate : function (dateTemp, timeZone) {
        //dateTemp(String) -> 2016-09-12 15:00:00.0 (UTC date)
        //timezone(String) -> -08:00
        var tempNow = moment(dateTemp);
        //create moment in current timeZone (without change in date)
        //offset -> 330 (IST)
        var dateToTimezone = tempNow.clone();
        dateToTimezone.utcOffset('UTC');
        //convert moment in UTC
        //offset -> 0
        dateToTimezone.add(tempNow.utcOffset() -dateToTimezone.utcOffset(), 'minutes');
        var revertTime = moment(dateToTimezone);
        //converted to user selected timeZone
        revertTime.utcOffset(timeZone);
        var dateToTimezone = revertTime.format();
        //converted to other timeZone
        return dateToTimezone;
}

Output

1) To -08:00 offset

2016-09-12 15:00:00.0 -> 2016-09-12T07:00:00-08:00

2) To -02:00 offset

2016-09-12 15:00:00.0 -> 2016-09-12T13:00:00-02:00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM