How to get user timezone using jquery?

前端 未结 6 2084
长发绾君心
长发绾君心 2020-11-30 11:03

I would like to get their timezone with names like \'Asia/Calcutta\' or \'Australia/Darwin\'

I have php installed on myserver and i

6条回答
  •  不知归路
    2020-11-30 11:20

    You do not need jQuery to do this. Try the following code:

    var offset = (new Date()).getTimezoneOffset();
    alert(offset);
    

    It will alert current timezone offset from the browser (in minutes).

    See this jsfiddle as a proof.

    I think you will need to convert it to the timezone name on your own. If you want the names to be consistent, you should not depend on the user's browser.

    You can use this code (see this jsfiddle):

    var offset = (new Date()).getTimezoneOffset();
    
    var timezones = {
        '-12': 'Pacific/Kwajalein',
        '-11': 'Pacific/Samoa',
        '-10': 'Pacific/Honolulu',
        '-9': 'America/Juneau',
        '-8': 'America/Los_Angeles',
        '-7': 'America/Denver',
        '-6': 'America/Mexico_City',
        '-5': 'America/New_York',
        '-4': 'America/Caracas',
        '-3.5': 'America/St_Johns',
        '-3': 'America/Argentina/Buenos_Aires',
        '-2': 'Atlantic/Azores',
        '-1': 'Atlantic/Azores',
        '0': 'Europe/London',
        '1': 'Europe/Paris',
        '2': 'Europe/Helsinki',
        '3': 'Europe/Moscow',
        '3.5': 'Asia/Tehran',
        '4': 'Asia/Baku',
        '4.5': 'Asia/Kabul',
        '5': 'Asia/Karachi',
        '5.5': 'Asia/Calcutta',
        '6': 'Asia/Colombo',
        '7': 'Asia/Bangkok',
        '8': 'Asia/Singapore',
        '9': 'Asia/Tokyo',
        '9.5': 'Australia/Darwin',
        '10': 'Pacific/Guam',
        '11': 'Asia/Magadan',
        '12': 'Asia/Kamchatka' 
    };
    
    alert(timezones[-offset / 60]);
    

    However I would not rely on this too much.

提交回复
热议问题