Timezones and UTC in PHP

If you are dealing with multiple users in different timezones or simply want to display times in a timezone other than your server's settings, it is best to store timestamps as their UTC (~ GMT) equivalents. When you read those timestamps later, you can convert them to local time.

Local time to UTC time

PHP:
  1. date_default_timezone_set('Australia/Sydney');
  2. $time = gmmktime($hr, $min, $sec, $mon, $day, $yr);
  3. $date = gmdate('d/m/Y H:i', time());

date_default_timezone_set sets the default timezone for all date & time operations.
gmmktime is analogous to mktime except it takes in local time values and creates the corresponding UTC timestamp.
gmdate similarly takes in local time values and creates the corresponding UTC date & time.

UTC time to Local time

PHP:
  1. $ts_utc = read_timestamp_from_db()//Some custom function in your script
  2. date_default_timezone_set('Australia/Sydney');
  3. $offset = date('Z');    //Timezone offset from UTC in number of seconds (can be +ve or -ve)
  4. $ts_local = $ts_utc + $offset;

Leave a Reply

Your email address will not be published. Required fields are marked *

*


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>