How to identify Daylight Saving Time in PHP
Today, We’ll explain you how to identify Daylight Saving Time in PHP. PHP provides a way to check whether time is in Daylight Savings Time or not.
Using the date()
function, we can check whether a timezone is in DST. We can also identify the DST for specific time zone or specific date.
Checkout more articles on PHP
Identify Daylight Saving Time
- Identify DST for current date
- Identify DST for specific time zone
- Identify DST for specific date
- Get time zone data including DST
1. Identify DST for current date
1 2 3 4 5 6 7 8 9 | <?php date('I'); // this will be 1 in DST or else 0 if (date('I')) { echo "We are in daylight saving time"; } else { echo "We are NOT in daylight saving time"; } exit; ?> |
Once you know you’re in daylight savings time, you can adjust your logic accordingly.
2. Identify DST for specific time zone
If you want to know if the US is in DST you can do the following. To check DST in the US, we need to set a Time Zone using date_default_timezone_set()
before the call date()
function.
1 2 3 4 5 | <?php date_default_timezone_set('America/New_York'); $dst = date('I'); print_r($dst); ?> |
3. Identify DST for specific date
If you want to check DST for perticular date then you can use like as below.
1 2 3 4 5 | <?php date_default_timezone_set('America/New_York'); $dst = date('I', strtotime('2022-11-06')); print_r($dst); ?> |
4. Get time zone data including DST
You can use the getTransitions()
function that gives you timezone data that contains DST flag.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php function timezone($timezone = 'America/New_York') { $tz = new DateTimeZone($timezone); $transitions = $tz->getTransitions(); if (is_array($transitions)) { foreach ($transitions as $k => $t) { // look for current year if (substr($t['time'], 0, 4) == date('Y')) { $trans = $t; break; } } } return (isset($trans)) ? $trans : false; } $timezone_Data = timezone(); print_r($timezone_Data); ?> |
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂