Question

I'm having one string like "IST GMT+5:30" and I want to convert it into something like 'Asia/Kolkata' or any Indian Time Zone.

What I was trying is

$userSubmittedTimezoneString='IST';
$userTimezone = new DateTimeZone($userSubmittedTimezoneString);
print_r($userTimezone);

When $userSubmittedTimezoneString='IST', it gives following output :

DateTimeZone Object ( [timezone_type] => 3 [timezone] => Asia/Jerusalem )

'Asia/Jerusalem' is a Israel Time Zone but what i want is India Standard Time.

Please help me to achieve this using php.

EDIT :

"IST GMT+5:30" is dynamic. It comes from database.

Was it helpful?

Solution

Because timezone abbreviations are not unique, and neither are timezone offsets, there is no solution that is completely robust and guaranteed to work in all scenarios.

For instance, in this scenario, the timezones Asia/Colombo and Asia/Kolkata would match your offset and abbreviation. Other scenarios are much worse; for instance CET +01:00 covers over 50 timezone identifiers across Europe and Africa.

If you don't know what datetime your abbreviation and offset was referring to, then you've got another problem: DST. For instance, you'd only be able to match BST +01:00 if you knew that it applied to a date in British Summer Time.

However, if you accept the above issues, then you can have a guess at the timezone:

function findTimezone($offset, $date = 'now', $countries = \DateTimeZone::ALL) {
    foreach (\DateTimeZone::listIdentifiers($countries) as $timezone) {
        $datetime = new \DateTime($date, new \DateTimeZone($timezone));

        // find a timezone matching the offset and abbreviation
        if ($offset == $datetime->format('T P')) {
            return $timezone;
        }
    }
}

var_dump(findTimezone('IST +05:30', '2014-04-22 00:00:00'));

This returns the first timezone that matches the given abbreviation and offset.

If you haven't stored the datetime with the offset, then the above may give the correct result in some cases, but you might need to try more than one date before you found a match (e.g. 1 January and 1 July).

In summary: no such "conversion" exists, but an educated guess is certainly possible, given a number of caveats.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top