Hi,
I’m struggeling trying to write a function that based on the server’s timestamp calculates what the current time in GMT/UTC is. I have tried many approaches (all as part of a DateTime-class):
Go 1:
function getServerTime()
{
$this->timestamp = time();
$this->timestamp += SERVER_TIMEZONE;
// Take care of DST
$ar = localtime($this->timestamp, true);
if ($ar['tm_isdst'])
$this->timestamp += 3600;
return $this->timestamp;
}
The theory: Take the current time, add the timezone value for the server (expressed in second), check if it’s DST and if, add another hour. Done. But it gives the wrong time, 11:00:00 instead of 09:00:00.
Go 2:
function getGMT($timestamp) {
$last_day_of_march = gmmktime(1, 0, 0, 3, 31, gmdate('Y', $timestamp));
$last_sunday_of_march = $last_day_of_march - (gmdate('w', $last_day_of_march) * 86400);
$last_day_of_october = gmmktime(1, 0, 0, 10, 31, gmdate('Y', $timestamp));
$last_sunday_of_october = $last_day_of_october - (gmdate('w', $last_day_of_october) * 86400);
if ($timestamp > $last_sunday_of_march && $timestamp < $last_sunday_of_october) {
// Its DST For GMT So Add 1 Hour
$timestamp += 3600;
}
return $timestamp;
}
echo gmdate('F j, Y, g:i a', getGMT(time()));
Closer now. Returns 10:00:00 when 09:00:00 is expected. Off by one hour instead of two.
Go 3:
function getServerTimeAsGMT()
{
$timestamp = localtime();
$timestamp[5] += 1900;
$timestamp[4]++;
for ($i = 0; $i <= 9; $i++)
{
if ($timestamp[0] == $i)
{
$newValue = "0" . $i;
$timestamp[0] = $newValue;
}
}
for ($i = 0; $i <= 9; $i++)
{
if ($timestamp[1] == $i)
{
$newValue = "0" . $i;
$timestamp[1] = $newValue;
}
}
$this->timestamp = $timestamp[5] . "-" . $timestamp[4] . "-" . $timestamp[3] . " " . $timestamp[2] . ":" . $timestamp[1] . ":" . $timestamp[0];
$this->timestamp = strtotime($this->timestamp);
return $this->timestamp;
}
Wow! This actually works. But I can’t understand why, how hard I look at the code. There is nothing that takes notice of the timezone of the server, and nothing that bothers about daylight savings time. How - on earth - can this code return the current GMT? My guess is that it’s a coinsidence(sp?) rather than 100 percent working code.
So: What’s the safest bet to get current GMT?
For a guestbook I’m writing, I want to store timestamps as GMT in MySQL so that for each user I can display times according to his/her timezone.