4

I was under the impression that the format() function of the PHP DateTime class exported the timestamp it was initially passed with the correct offset applied to it.

I've come to realise that it doesn't make sense for it to do that. I therefore want to store the timestamp from the database (UTC) in the object along with the user's timezone, and be able to output it according to whether I want a UTC date or a user timezone adjusted date.

I've begun extending the DateTime class to do this but I'm wondering if I'm missing something in either the existing methods in DateTime or the thought process behind why the DateTime class works the way it does.

Presumably I'll also need a couple of static factory methods which can take a timestamp, timezone and whether the timestamp passed in is a user adjusted timestamp or a UTC timestamp, and be able to make the necessary adjustments to instantiate a standardised DateTime object from the UTC version of the time passed in. In this way I'd be able to throw timestamps around the UI and database and be able to convert between them appropriately.

Is there a simpler way? I've seen the date_default_timezone_set function but I want to avoid having that setting affect the whole script, leading to user adjusted times being stored in the DB.

(I'm storing users' timezones in the DB as the timezone string, such as Europe/Berlin, to pass into the functions from a user session variable. I also intend to store all datetimes as UTC times and leave the server's php.ini set to UTC as well.)

1 Answer 1

7

You can create the DateTime instance, specifying that it is UTC. Then change its timezone to that of the user with setTimeZone().

$datetime = new DateTime("2011-06-07 12:34:56", new DateTimeZone("UTC"));
$datetime->setTimeZone(new DateTimeZone("Europe/Berlin"));
echo $datetime->format(DateTime::RSS);
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, so that's what I've been missing. Initialize it with the starting timezone and then set it to use the end timezone.
Absolutely, it's generally really that simple but a common enough question that gets asked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.