tags:

views:

623

answers:

3

In PHP, how do I get the current time, in UTC, without hard coding knowledge of where my hosting provider is?

For example, I tried the following:

time() + strtotime('January 1, 2000')-strtotime('January 1, 2000 UTC')

and find that it reports a time that is one hour ahead of actual UTC time. I tried this on two different hosting providers in two different time zones with the same results.

Is there a reliable (and, hopefully, cleaner) way to accurately get the UTC time?

I am limited to PHP 4.4.9 so I cannot use the new timezone stuff added to PHP5.

Thanks, in advance.

+3  A: 

This seems to work for me. Of course, you'll need to test it on PHP 4 since all of my servers have PHP 5, but the manual claims this should work for PHP 4.

$t = time();
$x = $t+date("Z",$t);
echo strftime("%B %d, %Y @ %H:%M:%S UTC", $x);

First time around, I forgot that the date could change between the call to time() and date().

Tom
Much better then using `date("T")`. Well worth a +1.
MitMaro
Thanks, and I had given you a +1 for the comment above.
Tom
Thanks, it works. :)
Dave
I was just browsing through the PHP Manual and ran accross gmdate. So, something like this: echo gmdate("H:i:s")." UTC"; should work as well.
Tom
+1  A: 
$time = new DateTime('now', new DateTimeZone('UTC'));
echo $time->format('F j, Y H:i:s');
GZipp
Thanks for your answer. Although this doesn't work for PHP 4.4.9, it does work fine on the other PHP 5.2.
Dave
Sorry, apparently my reading comprehension was off when I read your question. Glad to have helped anyway.
GZipp
A: 
$utcTtime = gmmktime();
$localTime = time();

gmmktime: Get Unix timestamp for a GMT date

Stefan Gehrig