Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a DateTimeZone from an offset?

Tags:

php

datetime

The DateTimeZone constructor only accepts a region name:

new DateTimeZone('Europe/London');

And not an offset from UTC:

new DateTimeZone('+01:00'); // Unknown or bad timezone (+01:00)

However, it is possible to obtain such a DateTimeZone from a DateTime:

(new DateTime('2012-12-28T00:00:00+01:00'))->getTimezone()->getName(); // +01:00

So this is a bit weird. Is there a way to directly obtain a DateTimeZone from an offset?

like image 220
BenMorel Avatar asked Dec 28 '12 11:12

BenMorel


3 Answers

In addition to Rafał's answer, the simplest way I've found so far is:

DateTime::createFromFormat('O', '+01:00')->getTimezone();

Edit

This was a bug that has been fixed in PHP 5.5.10. It now works!

like image 154
BenMorel Avatar answered Oct 10 '22 20:10

BenMorel


Modern answer:

new DateTimeZone('+0100');

Documentation:

http://php.net/manual/en/datetimezone.construct.php

like image 2
William Entriken Avatar answered Oct 10 '22 18:10

William Entriken


Check out this function.

http://pl1.php.net/manual/en/function.timezone-name-from-abbr.php

You'll need to convert hours to seconds and pass them as second parameter.

Sth. like new DateTimeZone(timezone_name_from_abbr('', 3600, 0)) should work.

like image 1
Rafał Toboła Avatar answered Oct 10 '22 20:10

Rafał Toboła