SMSM
SMSM

Reputation: 1529

How can I detect day light savings automatically in PHP?

How can I detect day light savings automatically in PHP?

Upvotes: 38

Views: 30119

Answers (2)

Cully
Cully

Reputation: 6975

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

Upvotes: 9

Glycerine
Glycerine

Reputation: 7347

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.

Upvotes: 83

Related Questions