Can anyone suggest an easy method to convert date and time to different timezones in php?
This worked for me and it's pretty clean too!
function convert_to_user_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
{
try {
$dateTime = new DateTime ($date, new DateTimeZone($serverTimeZone));
$dateTime->setTimezone(new DateTimeZone($userTimeZone));
return $dateTime->format($format);
} catch (Exception $e) {
return '';
}
}
function convert_to_server_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
{
try {
$dateTime = new DateTime ($date, new DateTimeZone($userTimeZone));
$dateTime->setTimezone(new DateTimeZone($serverTimeZone));
return $dateTime->format($format);
} catch (Exception $e) {
return '';
}
}
//example usage
$serverDate = $userDate = '2014-09-04 22:37:22';
echo convert_to_user_date($serverDate);
echo convert_to_server_date($userDate);
I always struggle to remember how exactly setTimezone()
method works. Is it adjusting datetime according to timezone? Or does it take a given datetime, drops its timezone, and uses the one you pass? All in all, I'd rather have a more intuitive way to work with timezones.
I like this one:
(new AdjustedAccordingToTimeZone(
new DateTimeFromISO8601String('2018-04-25 15:08:01+03:00'),
new Novosibirsk()
))
->value();
It outputs a datetime in ISO8601 format, in Novosibirsk timezone.
This approach uses meringue library, check out a quick start for more examples.
<?php
$time='6:02';
$dt = new DateTime($time, new DateTimeZone('America/New_York'));
//echo $dt->format('Y-m-d H:i:s') . PHP_EOL;
$dt->setTimezone(new DateTimeZone('Asia/Kolkata'));
echo $dt->format('H:i') . PHP_EOL;
?>