Determine a user's timezone

前端 未结 25 3369
刺人心
刺人心 2020-11-21 07:12

Is there a standard way for a web server to be able to determine a user\'s timezone within a web page?

Perhaps from an HTTP header or part of the user-agent

25条回答
  •  深忆病人
    2020-11-21 07:22

    Here is a more complete way.

    1. Get the timezone offset for the user
    2. Test some days on daylight saving boundaries to determine if they are in a zone that uses daylight saving.

    An excerpt is below:

    function TimezoneDetect(){
        var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear());
        var intOffset = 10000; //set initial offset high so it is adjusted on the first attempt
        var intMonth;
        var intHoursUtc;
        var intHours;
        var intDaysMultiplyBy;
    
        // Go through each month to find the lowest offset to account for DST
        for (intMonth=0;intMonth < 12;intMonth++){
            //go to the next month
            dtDate.setUTCMonth(dtDate.getUTCMonth() + 1);
    
            // To ignore daylight saving time look for the lowest offset.
            // Since, during DST, the clock moves forward, it'll be a bigger number.
            if (intOffset > (dtDate.getTimezoneOffset() * (-1))){
                intOffset = (dtDate.getTimezoneOffset() * (-1));
            }
        }
    
        return intOffset;
    }
    

    Getting TZ and DST from JS (via Way Back Machine)

提交回复
热议问题