How to find timezone ID from IP address/country name in PHP?

后端 未结 4 519
北荒
北荒 2020-12-02 01:40

Can anyone please tell me if there is any way available in PHP to fetch timezone region like(\'Asia/Calcutta\') from IP Address or country name?

Description:

<
4条回答
  •  星月不相逢
    2020-12-02 02:27

    I consider a better idea is to finding out which timezone is set based on the user client setting. Maybe there is the situation that a user is in a timezone, which he doesn't want to be.

    One simple possibility is to ask the user, but that's to easy.

    With JavaScript you could find out the offset in minutes from UTC. Also you could find out, if the client is in a country with daylight saving time (DST) and if dst is active. This could be done, by comparing the time of two date objects, one with the month January and one with the month July.

    var dst1, dst2, expires, hemisphere, now;
    
    now = new Date(); expires = new Date(); dst1 = new Date(); dst2 = new Date();
    
    expires.setTime(now.getTime() + 31536000000);
    setCookie('timezone_offset', now.getTimezoneOffset(), expires, '/');
    
    dst1.setDate(1);
    dst1.setMonth(1);
    dst2.setDate(1);
    dst2.setMonth(7);
    
    if (parseInt(dst1.getTimezoneOffset()) === parseInt(dst2.getTimeZoneOffset())) {
      setCookie('timezone_dst', 0, expires, '/');
    } else {
      hemisphere = parseInt(d1.getTimezoneOffset()) - parseInt(d2.getTimezoneOffset());
      if ((hemisphere > 0 && parseInt(d1.getTimezoneOffset()) === parseInt(now.getTimezoneOffset())) || (hemisphere < 0 && parseInt(d2.getTimezoneOffset()) === parseInt(now.getTimezoneOffset()))) {
        setCookie('timezone_dst', '0', expires, '/');
      } else {
        setCookie('timezone_dst', '1', expires, '/');
      }
    }
    

    Read the cookie with PHP and interpreting the information of them with timezone_name_from_abbr():

    $timezone = timezone_name_from_abbr('', $_COOKIE['timezone_offset'] * 60, $_COOKIE['timezone_dst']);
    

提交回复
热议问题