问题
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?
回答1:
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'
回答2:
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()
.
回答3:
Both are correct. In the code snippet PHP adjusts for timezone. Try date_default_timezone_set('UTC');
to get proper unadjusted values.
回答4:
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
回答5:
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.
来源:https://stackoverflow.com/questions/4757078/get-the-correct-hour-for-a-unix-timestamp