Skip to content

Instantly share code, notes, and snippets.

@flacodirt
Last active December 14, 2015 22:58
Show Gist options
  • Save flacodirt/5161881 to your computer and use it in GitHub Desktop.
Save flacodirt/5161881 to your computer and use it in GitHub Desktop.
Datetime conversion methods. Convert server datetime to UTC and convert UTC to server datetime.
/**
* Datetime conversion methods. Convert server datetime to UTC and convert UTC to server datetime.
* @author https://gist.github.com/dirte/
* @version 1.0.1
* @category DateTime
*/
/**
* datetimeConvertServerToUTC
*
* @example $utc = datetimeConvertServerToUTC();
* @return date UTC datetime of NOW in format YYYY-MM-DD HH:MM:SS
* @todo optional param for desired timezone to convert server value to
* @todo optional param for desired return datetime format
*/
function datetimeConvertServerToUTC() {
return $gmdate = gmdate("Y-m-d H:i:s");
}
/**
* datetimeConvertUTCToServer
*
* @example datetimeConvertUTCToServer($utc);
* @var timezone Default timezone to use if server datetime not configured in php.ini
* @param date $utcDatetime UTC datetime
* @return date $serverDatetime
* @todo optional param for desired timezone to convert UTC value to
* @todo optional param for desired return datetime format
*/
function datetimeConvertUTCToServer($utcDatetime) {
// Attempt to use date.timezone declared in servers php.ini
$TZ = ini_get('date.timezone');
// Manually set our own timezone if server does not declare a default
if (empty($TZ)):
$TZ = new DateTimeZone('America/New_York');
endif;
// UTC DateTime
$utcDatetime = new DateTime($utcDatetime, new DateTimeZone('UTC'));
// Converted UTC DateTime to Server DateTime
$serverDatetime = clone $utcDatetime;
$serverDatetime->setTimezone($TZ);
return $serverDatetime->format("Y-m-d H:i:s");
}
/**
* Example usage:
*/
$utc = datetimeConvertServerToUTC();
echo 'datetimeConvertServerToUTC(): '.$utc.'<hr />';
echo 'datetimeConvertUTCToServer(): '.datetimeConvertUTCToServer($utc);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment