Change timezone without changing the value of a DateTime object
Asked Answered
C

1

7

Here's the scenario - I have the default timezone in PHP set to UTC. All but one date/time that I work with are set to the current UTC time; when displayed later on, I set the timezone for that particular user and the date comes out in their timezone. Works great.

Except I have one date/time that the user can enter on a form. It comes in as "YYYY-MM-DD HH:MM" in 24 hour time (example: "2014-09-18 17:00"). The user is naturally setting this time in their timezone, not UTC.

If I create a new DateTime object with the input value, it saves in UTC, so when displayed later it's off by several hours (depending on the original timezone). If I set the timezone on the new object, it alters the value, assuming, again, that the input value was UTC.

I've done some Googling but have found nothing in regards to PHP (several answers for C# exist that I've found). Is this possible with the DateTime object (or with Carbon)? Am I stuck with doing a manual addition/subtraction of hours based on the users current timezone to place it in UTC first?

Cailly answered 19/9, 2014 at 16:57 Comment(0)
J
13

You must set timezone when creating DateTime object, and not when it is already created; then change DateTime object to UTC timezone and save it to you db:

# create DateTime based on user timezone
$dt = new DateTime('2014-09-18 17:00', new DateTimezone('Australia/Sydney'));
# change time to UTC timezone
$dt->setTimezone(new DateTimezone('UTC'));
Judon answered 20/9, 2014 at 5:40 Comment(2)
Somehow I completely missed that option in the DateTime constructor. Thanks!Cailly
Thank you!!! I didn't realize the solution was this simple..Yachting

© 2022 - 2024 — McMap. All rights reserved.