Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change timezone without changing the value of a DateTime object

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?

like image 720
Nathan Loding Avatar asked Sep 19 '14 16:09

Nathan Loding


People also ask

How do I change the timezone without changing the time in Java?

DateTimeZone timeZone = DateTimeZone. forID( "Australia/Sydney" ); String input = "2014-01-02T03:00:00"; // Note the lack of time zone offset at end. DateTime dateTime = new DateTime( input, timeZone );

How do I change the timezone to a datetime object?

Timezone aware object using datetime now(). time() function of datetime module. Then we will replace the value of the timezone in the tzinfo class of the object using the replace() function. After that convert the date value into ISO 8601 format using the isoformat() method.

How do I make my timezone aware?

To make them timezone-aware, you must attach a tzinfo object, which provides the UTC offset and timezone abbreviation as a function of date and time. For zones with daylight savings time, python standard libraries do not provide a standard class, so it is necessary to use a third party library.


1 Answers

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'));
like image 165
Glavić Avatar answered Sep 20 '22 02:09

Glavić