Skip to content

Instantly share code, notes, and snippets.

@oojacoboo
Created February 14, 2013 04:35
Show Gist options
  • Select an option

  • Save oojacoboo/4950629 to your computer and use it in GitHub Desktop.

Select an option

Save oojacoboo/4950629 to your computer and use it in GitHub Desktop.
/**
* Convert date/time to user's timezone
*
* @access public
* @param mixed $dateTime
* @param string $format
* @return string
*/
public function toUserTimezone($dateTime, $format) {
//validate date/time value
if($dateTime === null)
return null;
//set default format and server timezone values, don't include timezone
$df = 'Y-m-d H:i:s';
$tz = self::getTimezone();
//convert to date/time default format first
$dateTime = $dateTime instanceof DateTime ? date($df, $dateTime->format("U")) : ensureDateTime($dateTime, $df);
//re-validate the date/time string to make sure we can use
if(isValidDateTime($dateTime) === false)
return $dateTime; //catches edge cases where strings like "Never" are passed
//if invalid timezone, then do not convert
//remember that by design date/time always converted from server time to user time
//so if timezone if invalid, then we should just return original value in a requested format
if(!in_array($tz, DateTimeZone::listIdentifiers()))
return date($format, strtotime($dateTime));
//initialize date/time object using server's timezone
$dt = new DateTime($dateTime);
$dt->setTimezone(new DateTimeZone($tz));
Debug::toLog($dt);
Debug::toLog(date("Y-m-d H:i:s", $dt->format($format)));
//return converted date/time value
return $dt->format($format);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment