I am in need of an easy way to convert a date time stamp to UTC (from whatever timezone the server is in) HOPEFULLY without using any libraries.
General purpose normalisation function to format any timestamp from any timezone to other.
Very useful for storing datetimestamps of users from different timezones in a relational database. For database comparisons store timestamp as UTC and use with gmdate('Y-m-d H:i:s')
/**
* Convert Datetime from any given olsonzone to other.
* @return datetime in user specified format
*/
function datetimeconv($datetime, $from, $to)
{
try {
if ($from['localeFormat'] != 'Y-m-d H:i:s') {
$datetime = DateTime::createFromFormat($from['localeFormat'], $datetime)->format('Y-m-d H:i:s');
}
$datetime = new DateTime($datetime, new DateTimeZone($from['olsonZone']));
$datetime->setTimeZone(new DateTimeZone($to['olsonZone']));
return $datetime->format($to['localeFormat']);
} catch (\Exception $e) {
return null;
}
}
Usage:
$from = ['localeFormat' => "d/m/Y H:i A", 'olsonZone' => 'Asia/Calcutta']; $to = ['localeFormat' => "Y-m-d H:i:s", 'olsonZone' => 'UTC']; datetimeconv("14/05/1986 10:45 PM", $from, $to); // returns "1986-05-14 17:15:00"
Use strtotime to generate a timestamp from the given string (interpreted as local time) and use gmdate to get it as a formatted UTC date back.
As requested, here’s a simple example:
echo gmdate('d.m.Y H:i', strtotime('2012-06-28 23:55'));
With PHP 5 or superior, you may use datetime::format function (see documentation http://us.php.net/manual/en/datetime.format.php)
echo strftime( '%e %B %Y' ,
date_create_from_format('Y-d-m G:i:s', '2012-04-05 11:55:21')->format('U')
); // 4 May 2012
Using DateTime:
$given = new DateTime("2014-12-12 14:18:00");
echo $given->format("Y-m-d H:i:s e") . "\n"; // 2014-12-12 14:18:00 Asia/Bangkok
$given->setTimezone(new DateTimeZone("UTC"));
echo $given->format("Y-m-d H:i:s e") . "\n"; // 2014-12-12 07:18:00 UTC
Follow these steps to get UTC time of any timezone set in user's local system (This will be required for web applications to save different timezones to UTC):
Javascript (client-side):
var dateVar = new Date();
var offset = dateVar.getTimezoneOffset();
//getTimezoneOffset - returns the timezone difference between UTC and Local Time
document.cookie = "offset="+offset;
Php (server-side):
public function convert_utc_time($date)
{
$time_difference = isset($_COOKIE['offset'])?$_COOKIE['offset']:'';
if($time_difference != ''){
$time = strtotime($date);
$time = $time + ($time_difference*60); //minutes * 60 seconds
$date = date("Y-m-d H:i:s", $time);
} //on failure of js, default timezone is set as UTC below
return $date;
}
..
..
//in my function
$timezone = 'UTC';
$date = $this->convert_utc_time($post_date); //$post_date('Y-m-d H:i:s')
echo strtotime($date. ' '. $timezone)
http://php.net/manual/en/function.strtotime.php or if you need to not use a string but time components instead, then http://us.php.net/manual/en/function.mktime.php