get timezone offset of another timezone in javascript without using Strings

Viewed 12060

I want to calculate the offset from 'users time' to 'WET/WEST'.

I get the users offset with new Date().getTimezoneOffset().

But how do I get the offset for WET/WEST So that I can calcluate the combined offset of both?

For example, if the user is in central europe time (CET/CEST), in winter the combined offset would be -60 (CET) + 0 (WET) = -60. In summer, it would be -120 (CEST) + 60 (WEST) = -60. In this case it is always -60 but the user could also have a timezone without DST.

Is this possible without format it to a string and read out the new timezone from that string?

3 Answers

I wanted to without a library too, but even with moment it has a fixed amount of timezone data so will break after 30 years if you don't keep updating, just erks me a bit. although this does use strings, nothing more complicated than parsing a string which is just an number

function getTimezoneOffset(dt, timezone) {

     let getItem = function(format) {
         format.timeZone = timezone;
         return parseInt(dt.toLocaleString(
            'en-US', format));
     };
    
     let adjDate = new Date(
        getItem({year: 'numeric'}),
        getItem({month: 'numeric'}) - 1, // months are zero based
        getItem({day: 'numeric'}),
        getItem({hour: 'numeric',hour12: false}),
        getItem({minute: 'numeric'}));
     let noSecs = new Date(dt.getTime());
     noSecs.setSeconds(0, 0);
     let diff = Math.round((adjDate.getTime() - noSecs.getTime()) / 60000);
    
     return dt.getTimezoneOffset() - diff;
    
}

I wanted to do this without using a library, so I wrote this function that gives you the timezone offset between the given timezone and utc:

function getTimezoneOffsetFrom(otherTimezone) {
    if (otherTimezone === void 0) { otherTimezone = "Europe/Amsterdam"; }
    var date = new Date();
    function objFromStr(str) {
        var array = str.replace(":", " ").split(" ");
        return {
            day: parseInt(array[0]),
            hour: parseInt(array[1]),
            minute: parseInt(array[2])
        };
    }
    var str = date.toLocaleString(['nl-NL'], { timeZone: otherTimezone, day: 'numeric', hour: 'numeric', minute: 'numeric', hour12: false });
    var other = objFromStr(str);
    str = date.toLocaleString(['nl-NL'], { day: 'numeric', hour: 'numeric', minute: 'numeric', hour12: false });
    var myLocale = objFromStr(str);
    var amsterdamOffset = (other.day * 24 * 60) + (other.hour * 60) + (other.minute);
    var myLocaleOffset = (myLocale.day * 24 * 60) + (myLocale.hour * 60) + (myLocale.minute);
    return myLocaleOffset - amsterdamOffset + date.getTimezoneOffset();
}

Maybe it can be approved by using en-US as a locale string and then the str.replace maybe needs to filter a comma or something.

Related