PHP date() function ignores the timestamp parameter
The output of the following program can be seen here: http://codepad.org/egNGJBUL
<?php
/* Checking if time() is really timezone independent */
date_default_timezone_set('UTC');
echo time();
echo "\n";
date_default_timezone_set('Australia/Queensland');
echo time();
echo "\n";
/* Using date() function passing timestamp parameter */
date_default_timezone_set('UTC');
echo date('Y-m-d H:i:s',time());
echo "\n";
date_default_timezone_set('Australia/Queensland');
echo date('Y-m-d H:i:s',time());
echo "\n";
/* Using date() function without passing timestamp parameter */
date_default_timezone_set('UTC');
echo date('Y-m-d H:i:s');
echo "\n";
date_default_timezone_set('Australi开发者_开发知识库a/Queensland');
echo date('Y-m-d H:i:s');
echo "\n";
From line 1-2 of the output, we can see time()
returns a value which is really timezone independent.
In line 3-4, it's strange that date()
function ignores the timestamp parameter and still display the date time according to the timezone set.
Why is it like this?
Not really sure what you are expecting to see, but yes, looks very normal to me.
A timestamp is a integer counted from a certain point in time (usually the UNIX EPOCH). While the display of this value is timezone independent, it is no more or less so that say, the value of a properly formatted date, notated with a timezone, is timezone independent...
example, all of the following statements are both true (logically)
1297799809 == 1297799809
2011-02-15 19:56:49 (UTC) == 2011-02-16 05:56:49 (Austria/Queensland)
All time is 'timezone independant'. Timezones only affect the way we display a particular moment in time.
date()
functions second parameter, if not specified, is time()
value.
date() Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().
from date()'s manual
So actually nothing is being ingnored.
The date function returns the date of a timestamp calculated for the current timezone, as others have said, if no timestamp is passed to it, then the current time is used for the timestamp, so passing time()
is the same as not passing anything at all.
However, doing something like $time = time();sleep 5;echo date($format,$time);
will get you a date 5 seconds in the past.
It's meant to display the date formatted for current timezone so you can have a universal method of keeping time that's constant across computers/servers and be easily parsable, and yet be able to display the date in any timezone desired.
The UTC timezone is actually the time that the timestamp is calculated to, more precisely, the number of seconds since 00:00 Jan 1, 1970 UTC, then it adds or subtracts 3600 (60*60) seconds from/to the timestamp per hour offset from UTC time to get the time in the currently set timezone.
精彩评论