How to get user locale time from UTC Time

|
| By Webner

How to get user locale time from UTC Time

The default timezone in Php or MySql is UTC (UTC doesn’t use daylight saving). But it can be troublesome when this is to be displayed to the user. E.g. – A user in New York accesses your website on 31st Dec 2017 9:30 AM and this will be saved in MySQL as 1st Jan 2018 2:30AM (UTC). Now when displaying same to the user as his/her last access date it can be confusing as by default it will displayed in UTC.

To display CakePHP default locale time in user’s locale, we can use the following code.

The Jquery Date object has various methods to get date and time.

	var timezone_offset_minutes = new Date().getTimezoneOffset()

The method getTimezoneOffset returns the minutes offset between the UTC time and the current user’s browser time. For instance, If UTC time is 11:40 AM and User browser Locale time is 10:30 AM then this method will return the offset 80 (minutes).

Send this timezone_offset_minutes using ajax call to Server Side.

Now in PHP we can use the following code by which we can get the TimeZone from the timezone offset minutes.

Example:

$timezone_offset_minutes = 330; //Calculated in Jquery;
$abbr = “ET”; timezone abbreviation if you already know the locale e.g. ‘UTC’
$timezone = timezone_name_from_abbr("$abbr", $timezone_offset_minutes*60, false); // Gives timezone name e.g. ‘Asia/Calcutta’
$utcTime = 2018-05-17 1:30 PM
$date = new DateTime($utcTime, new DateTimeZone($timezone));
$currentTime = $date->format('Y-m-d H:i:A');
echo $currentTime; //2018-05-17 7:00 PM; according to Asia/Calcutta timezone.

Leave a Reply

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