Nate
Nate

Reputation: 28384

Is time() independent of time zone settings?

I know the time zone can be changed by the following methods (and maybe more):

  1. Set putenv() with the time zone in every php file.
  2. Set date.timezone with the time zone in php.ini.
  3. Set php_value date.timezone with the time zone in the root .htaccess file.

My question is, does setting the time zone only affect the date() function, or does it also affect the time() function?

I read the documentation, but I'm still a little confused.. I think the answer is the former, but I need to make sure, so it would be great if someone could confirm this.

Thanks!

Upvotes: 5

Views: 4948

Answers (4)

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15301

time() isn't affected by timezone. functions like date, convert the resulting date to the timezone without affecting the timestamp.

<?php
var_dump(date_default_timezone_get());

$time1 = time();
var_dump($time1);
var_dump(date("r", $time1));

date_default_timezone_set("America/Los_Angeles");
var_dump(date_default_timezone_get());

$time2 = time();
var_dump($time2);
var_dump(date("r", $time1));

var_dump($time1 === $time2);

Outputs:

string(16) "Europe/Amsterdam"
int(1571676424)
string(31) "Mon, 21 Oct 2019 18:47:04 +0200"
string(19) "America/Los_Angeles"
int(1571676424)
string(31) "Mon, 21 Oct 2019 09:47:04 -0700"
bool(true)

Demo: https://3v4l.org/Cggc3

Upvotes: 9

Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

Since this is an absolute point in time, the seconds elapsed since then are (except for relativistic purposes) is unambigous. You will get the same value regardless of any timezone setting.

Upvotes: 3

Alain
Alain

Reputation: 36954

Try the following example :

date_default_timezone_set("Europe/Paris");
echo gmdate("H:i:s");
echo "<br/>";
echo date("H:i:s");
echo "<br/>";
echo time();

echo "<br/>";
echo "<br/>";

date_default_timezone_set("Asia/Chungking");
echo gmdate("H:i:s");
echo "<br/>";
echo date("H:i:s");
echo "<br/>";
echo time();

echo "<br/>";
echo "<br/>";

Displays :

18:52:38
19:52:38
1354647158

18:52:38
02:52:38
1354647159

Upvotes: 3

Omar Freewan
Omar Freewan

Reputation: 2678

php time() calculate the time using GMT so it is independent of what you set the timezone

Upvotes: 2

Related Questions