'Date Format PHP "I" to return DST always returns 0

I have the following code:

<?php
function dateIsDST ($timestamp=null, $timezone=null) {

    if (is_null($timestamp) && is_null($timezone)) {
        $date = new DateTime('@'.time());   
    }
    else {
        $date = new DateTime('@'.$timestamp, new DateTimeZone($timezone));
    }
    echo $date->format('Y-m-d H:i:sP');
    echo '---';
    // date("I") returns 1 in summer and 0 in winter
    var_dump ($date->format('I'));
}

dateIsDST(1648961437, 'America/New_York');
    
dateIsDST(1644861437, 'America/New_York');

But always returns 0 when it should return 1 (for the first method call).

2022-08-08 12:23:57+00:00---string(1) "0" // should be 1
2022-02-14 17:57:17+00:00---string(1) "0"

What am I doing wrong:

php


Solution 1:[1]

If you instantiate DateTime with a timestamp, the timezone is ignored. The fix is simple. Set the timezone with ->setTimeZone after instantiation in your function:

$date->setTimeZone(new DateTimeZone($timezone));

Result:

2022-04-03 00:50:37-04:00---string(1) "1"
2022-02-14 12:57:17-05:00---string(1) "0"

For reference, see PHP manual on DateTime::__construct:

The $timezone parameter and the current timezone are ignored when the $datetime parameter either is a UNIX timestamp (e.g. @946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

This happens because a Unix timestamp is always in UTC -- and for the intents of DateTime parsing, it's the same as specifying a timezone in your time string (= TZ argument is ignored).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1