How to change UTC time to your local time using PHP

How to change UTC time to your local time using PHP is big question in PHP programming language. Today, PHP Tricks provide you a simple and quick function to covert UTC/GMT time to your local time using  DateTimeZone  PHP class.

 

Suppose you get time in UTC/GMT time format from server and you want to convert it to your Local time So you just copy next function and follow instructions.

You should copy following function where need to pass UTC time (YYYY-mm-dd H:i:s format) and you will get local time in same format.

function gmdate_to_mydate($gmdate){
	/* $gmdate must be in YYYY-mm-dd H:i:s format*/
	$timezone=date_default_timezone_get();
	$userTimezone = new DateTimeZone($timezone);
	$gmtTimezone = new DateTimeZone('GMT');
	$myDateTime = new DateTime($gmdate, $gmtTimezone);
	$offset = $userTimezone->getOffset($myDateTime);
	return date("Y-m-d H:i:s", strtotime($gmdate)+$offset);
}

 

How to call this function ??

<?php 
   $date_in_gmt="2017-03-22 13:30:10"; //(YYYY-mm-dd H:i:s)
   echo gmdate_to_mydate($date_in_gmt); 

  //OUTPUT returns: 2017-03-22 19:00:10 
  // Because my time zone is GMT+5:30 
?>

Conclusion: Because my local time zone is GMT+5:30 (UTC+5:30) so this functions returns  my exact local time by adding 5 Hours and 30 mins in GMT/UTC time. 

This same function will return different local time according to countries or cities where executed.

By Ashutosh Pratap

I am software developer by profession and doing work and research in field of Computer programmings like PHP, WordPress, Magento, jQuery, Google APIs and many more web languages. Apart from this I write blogs on programming languages like PHP, Javascript, WordPress etc. I am also individual and independent Freelancer so you can hire me for your web work.

Leave a comment

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