Calculate the UTC offset given a TimeZone string in JavaScript

前端 未结 5 2071
感情败类
感情败类 2020-12-06 11:00

Using the standard JS library (ECMA5), without using momentjs or external libs, how do you calculate the UTC offset given a TimeZone string such as \"Europe/Rome\"

5条回答
  •  隐瞒了意图╮
    2020-12-06 11:42

    Youve got to:

    • get the current datetime (will give you the datetime in the current timezone of the current device)
    • get the current timezone offset
    • convert the datetime to the new/required timezone
    • get the difference between the current datetime and the converted datetime
    • add said difference to the current timezone offset

    Eg returning timezone in hours:

    function getTimezoneOffset(tz, hereDate) {
        hereDate = new Date(hereDate || Date.now());
        hereDate.setMilliseconds(0); // for nice rounding
    
        const
        hereOffsetHrs = hereDate.getTimezoneOffset() / 60 * -1,
        thereLocaleStr = hereDate.toLocaleString('en-US', {timeZone: tz}),
        thereDate = new Date(thereLocaleStr),
        diffHrs = (thereDate.getTime() - hereDate.getTime()) / 1000 / 60 / 60,
        thereOffsetHrs = hereOffsetHrs + diffHrs;
    
        console.log(tz, thereDate, 'UTC'+(thereOffsetHrs < 0 ? '' : '+')+thereOffsetHrs);
        return thereOffsetHrs;
    }
    
    
    getTimezoneOffset('America/New_York', new Date(2016, 0, 1));
    getTimezoneOffset('America/New_York', new Date(2016, 6, 1));
    getTimezoneOffset('Europe/Paris', new Date(2016, 0, 1));
    getTimezoneOffset('Europe/Paris', new Date(2016, 6, 1));
    getTimezoneOffset('Australia/Sydney', new Date(2016, 0, 1));
    getTimezoneOffset('Australia/Sydney', new Date(2016, 6, 1));
    getTimezoneOffset('Australia/Sydney');
    getTimezoneOffset('Australia/Adelaide');
    

    Which outputs like

    America/New_York 2015-12-30T22:00:00.000Z UTC-5
    America/New_York 2016-06-30T01:00:00.000Z UTC-4
    Europe/Paris 2015-12-31T04:00:00.000Z UTC+1
    Europe/Paris 2016-06-30T07:00:00.000Z UTC+2
    Australia/Sydney 2015-12-31T14:00:00.000Z UTC+11
    Australia/Sydney 2016-06-30T15:00:00.000Z UTC+10
    Australia/Sydney 2019-08-14T03:04:21.000Z UTC+10
    Australia/Adelaide 2019-08-14T02:34:21.000Z UTC+9.5
    

提交回复
热议问题