CristiC
CristiC

Reputation: 22698

Get the correct hour for a UNIX timestamp

I think this is a stupid question, but seems that I cannot find the answer.

I have this timestamp: 1295598602.

In my php script I have:

$date = date('Y-m-d', 1295598602); $hour = date('H', 1295598602) . ':00';

This returns:

Date: 2011-01-21
Hour: 03:00

Now I went to an online conversion site to test this. I used this one. But it seems that for this timestamp value it is

Fri, 21 Jan 2011 08:30:02 GMT

Now, which one is correct?

Upvotes: 3

Views: 10816

Answers (5)

Mark Northrop
Mark Northrop

Reputation: 2623

Another option is to set the default timezone for your script.

For example,

date_default_timezone_set('Europe/London');
$timestamp = '1295598602';
echo date('Y-m-d H:i:s', $timestamp);

would get you the same result as the online conversion tool is showing.

There are a number of timezone-related function in PHP that will allow you to modify which time zone is being shown.

You can check the PHP docs for a list of your options: http://www.php.net/manual/en/ref.datetime.php

Upvotes: 1

Novikov
Novikov

Reputation: 4489

Both are correct. In the code snippet PHP adjusts for timezone. Try date_default_timezone_set('UTC'); to get proper unadjusted values.

Upvotes: 1

Mchl
Mchl

Reputation: 62367

Use correct timezone:

>> date_default_timezone_get();
'UTC'
>> date('Y-m-d h:i:s',1295598602);
'2011-01-21 08:30:02'
>> date_default_timezone_set('CET');
true
>> date('Y-m-d h:i:s',1295598602);
'2011-01-21 09:30:02'
>> date_default_timezone_set('UTC');
true
>> date('Y-m-d h:i:s',1295598602);
'2011-01-21 08:30:02'

Upvotes: 6

Kel
Kel

Reputation: 7780

According to date() function description,

timestamp is optional and defaults to the value of time().

And according to time() function description, it returns GMT timestamp.

So, PHP does conversion to your time zone, while onlineconversion.com does not.

Upvotes: 0

Alnitak
Alnitak

Reputation: 339816

In GMT / UTC (they're almost but not quite exactly the same) that timestamp is indeed Fri, 21 Jan 2011 08:30:02 GMT.

If you're in a different timezone but always want GMT you'll need to use the gmdate() function instead of date().

Upvotes: 4

Related Questions