Quick conversion from UTC to local time in PHP

I ran across something in a work project where I was required to convert all times stored in UTC to the client’s local time zone. All of the PHP solutions involved multiple lines of code involved the DateTime and DateTimeZone classes, so in order to simplify that, I came up with the following:


$formatUTCDateTime = function($dts, $format = null, $tz = null) {
   if($format === null)
	  $format = 'Y-m-d H:i:s T';
 
   if($tz === null)
	  $tz = date_default_timezone_get();
 
   $dtz = new DateTimeZone('UTC');
   $dt = new DateTime($dts, $dtz);
   $dt->setTimezone(new DateTimeZone($tz));
 
   return $dt->format($format);
};

This method supports a default datetime format and will default the timezone to the currently configured timezone. This will be set dynamically according to the local time of the user (as set by date_default_timezone_set()) and will make the conversion process transparent.

No Comments

Leave a Reply

Your email is never shared.Required fields are marked *