默认时区不同时,时间戳是否应该更改? [重复]

This question already has an answer here:

Please understand, that this question wasn't answered there. Because if what they say in there would be true, timestamp should vary depending of timezone on given hour.

I got a problem with one project, because seems that timezone set on server was totally different then on machine where data is collected. Does timestamp change when default timezone changes in PHP? Should it or should it not?

php -r "date_default_timezone_set(\"Asia/Jakarta\");echo time();"
1397552668

php -r "echo time();"
1397552675

Seems it does not...am I right? Or am I doing something wrong?

Another test:

<?php
echo date_default_timezone_get();
echo " : ".time();
echo "
";
date_default_timezone_set("Asia/Jakarta");
echo date_default_timezone_get();
echo " : ".time();
echo "
";
?>

Result:

Europe/Berlin : 1397553155
Asia/Jakarta : 1397553155
</div>

Your problem seems to be a wrong assumption of what date_default_timezone_set does. But first start with how computers keep time:

  • the computer's BIOS typically keeps time, but is typically only set in date/hours/minutes without timezone information
  • when the computer's OS boots, it uses the BIOS's time as a starting point
  • the OS has a timezone setting, which tells it how to interpret the BIOS's time and figure out what the current absolute point in time is
    • note that some OSes interpret the BIOS's time as local time and others interpret the BIOS's time as UTC time; either way, BIOS time + OS timezone setting tells the OS what the current absolute time and the current local time is
  • modern OSes will occasionally contact an internet time server via NTP to get an absolutely universally correct time; it may adjust the BIOS's clock based on this if it differs
  • now that the OS has figured out what time it really is, it can give you the local time in any timezone you wish or the universal UNIX time

Now see Does PHP time() return a GMT/UTC Timestamp? for what the difference between "local" and "absolute" time is. Understanding that the OS deals with absolute time internally (likely in the form of a high-resolution UNIX timestamp) is critical. It does not keep time in the form of "HH:MM:SS", it only displays it as such based on your set timezone when it communicates times to you, a human.

What date_default_timezone_set does is simply choose the timezone in which human readable times are displayed. It does not change the OS's time or PHP's understanding of the current time or anything else. All it does is to tell PHP which timezone's local time to display when you do something like date('H:i').

UNIX timestamp is timezone independent so time() should always return same value. Other time manipulation functions (such as Date or Datetime) will depend on set timestamp, so if you do further manipulations with UNIX Timestamp, you will notice the difference.