开发者

How can I detect day light savings automatically in PHP?

开发者 https://www.devze.com 2022-12-28 21:10 出处:网络
How can I detect day light saving开发者_StackOverflows automatically in PHP?echo date(\'I\'); The I (capital i) is a 1/0 denoting whether or not daylight saving is currently in effect.

How can I detect day light saving开发者_StackOverflows automatically in PHP?


echo date('I');

The I (capital i) is a 1/0 denoting whether or not daylight saving is currently in effect.

http://php.net/manual/en/function.date.php

hope it helps.


This was posted as a comment to another answer. It's the correct answer and would be valuable for others to see. The answer currently marked as correct only works if you want to find out whether it's daylight saving time (DST) in the server/PHP timezone. It doesn't work for just any timezone (or if your server/PHP timezone is set to UTC).

date('I') will return "1" if the server/PHP timezone is in DST, or "0" if it isn't.

To find out if a specific timezone is in DST, use:

$date = new DateTime('now', new DateTimeZone('America/Los_Angeles'));
var_dump($date->format('I'));

Replace America/Los_Angeles with whatever timezone you're curious about.

To generalize this, and to get a boolean instead of a string:

function getIsDaylightSaving($timezoneStr = 'America/Los_Angeles') {
  $date = new DateTime('now', new DateTimeZone($timezoneStr));
  return (bool) $date->format('I');
}

NOTE: You could also use this method to find out if any date/time is in DST for a specific timezone. Just replace DateTime('now') with a specific date/time string. For example, to find out if 11:14pm on December 20th, 2021 is in DST for the USA Eastern Timezone:

$date = new DateTime('2020-12-20 23:14', new DateTimeZone('America/New_York'));
var_dump((bool) $date->format('I')); // returns false

// or a date/time that was in DST
$date = new DateTime('2020-03-20 23:14', new DateTimeZone('America/New_York'));
var_dump((bool) $date->format('I')); // returns true
0

精彩评论

暂无评论...
验证码 换一张
取 消