Question

I am storing timestamps in my db using UTC_TIMESTAMP().

I want to output them based on user selected timezone. I tried writing a small function to do this, however, it does not output correctly.

// Date/time converter
function convertTZ($date, $tz, $tzFormat)
{
$date = new DateTime($date);
$date->setTimezone(new DateTimeZone($tz));

return $date->format($tzFormat);
}

echo $_SESSION['dtCurrLogin'].'<br />';
echo convertTZ($_SESSION['dtCurrLogin'], 'UTC', 'F j, Y @ g:i:s a e');

dtCurrLogin from db = 2013-09-12 01:23:45

the above outputs :

2013-09-12 01:23:45 September 12, 2013 @ 5:23:45 am UTC

Obviously this is not correct as I went from UTC to UTC so they should be equal. If I change to output EST then it shows 1:23:45 am, but of course that would not be right either.

Was it helpful?

Solution

Didn't realize I needed to specify incoming timezone... using the following worked for me...

function convertTZ($date_time, $from_tz, $to_tz, $format_tz)
{
$time_object = new DateTime($date_time, new DateTimeZone($from_tz));
$time_object->setTimezone(new DateTimeZone($to_tz));
return $time_object->format($format_tz);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top