How to Convert Date Time Between Time Zones Using PHP

Managing datetime is easy in PHP but it is really hard to manage an app that has users from different time zone. If there is any kind of email or notification system, it should be proper. When users from different time zone work on the same app, you can allow them to select their timezone but the actual processing should be on the common time of the server. So, you must know how to change the datetime from one timezone to other.
In this article, I will show you this in PHP. Before you start, you must know that PHP has built-in support for timezone and timezone change. In PHP this easy with the DateTime standard library class. You can easily change time zone of the current script, convert time and more with few lines of code.
$datetimestr = '08/01/2017 03:08 PM'; $user_tz = 'America/Los_Angeles'; $schedule_date = new DateTime($triggerOn, new DateTimeZone($user_tz) ); $schedule_date->setTimeZone(new DateTimeZone('UTC')); $nwtime = $schedule_date->format('Y-m-d H:i:s'); echo $nwtime; // echoes 2017-08-01 22:08:00
The above code converts time from timezone Ameria/Los_Angeles to timezone UTC. you can change these values according to your own need.
To know the current timezone of the server, you can use the code given below.
if (date_default_timezone_get()) { echo 'current time zone: ' . date_default_timezone_get() . '<br />'; }
I think this is an easy way of handling PHP timezones at Server Density. How you do this? Let us know in the comments.
Further reading: http://php.net/manual/en/class.datetime.php
Leave a comment
Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.