user138821
user138821

Reputation: 444

In PHP, how can I get Timezone from offset and country?

I am doing an IP lookup to determine a "best guess" for timezone offset from UTC and the country/region information.

So, for instance, I have offset -3 and country Brazil.

I want to show BRT instead of a random timezone in that same offset, i.e. ART

Is there some built-in way in PHP to be able to set the appropriate timezone with this information?

If not, what would be the easiest way to do this? (Assume that I can't make any outside API calls)

If I do my own database table, how do I ensure it stays up to date?

Thanks!

Upvotes: 3

Views: 8140

Answers (3)

adilbo
adilbo

Reputation: 970

This PHP function give back an array of all existing Timezones including Offset, not exactly what you are looking for but maybe it helps:

function time_zonelist(){
    $return = array();
    $timezone_identifiers_list = timezone_identifiers_list();
    foreach($timezone_identifiers_list as $timezone_identifier){
        $date_time_zone = new DateTimeZone($timezone_identifier);
        $date_time = new DateTime('now', $date_time_zone);
        $hours = floor($date_time_zone->getOffset($date_time) / 3600);
        $mins = floor(($date_time_zone->getOffset($date_time) - ($hours*3600)) / 60);
        $hours = 'GMT' . ($hours < 0 ? $hours : '+'.$hours);
        $mins = ($mins > 0 ? $mins : '0'.$mins);
        $text = str_replace("_"," ",$timezone_identifier);
        $return[$timezone_identifier] = $text.' ('.$hours.':'.$mins.')';
    }
    return $return;
}

Upvotes: 1

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241890

You cannot resolve a timezone from an offset, or even an offset plus country. See the TimeZone != Offset section of the TimeZone tag wiki. The offsets have changed at many points in time, and they will inevitably change again.

You need more information, such as latitude/longitude. See this community wiki.

If you can ask your user for their timezone, please do. That's the best way. My favorite UI for this is a JavaScript map-based timezone picker, such as this one. You can make a best-guess default choice using jsTimeZoneDetect.

Upvotes: 2

Antony
Antony

Reputation: 15114

You don't have to roll your own database, here's one from GeoNames. You can also get all the timezone information from PHP.

Upvotes: 1

Related Questions