Question

In PHP, date('I') will tell me if Daylight Savings Time is in effect. Does this tell me if DST is in effect specifically for my server's configured timezone, or whether or not it's in effect period?

I'm in Arizona where we don't observe DST. So I need my server to recognize that, say, New York is 2 hours ahead of me right now, but when DST kicks in March next year that it's 3 hours ahead of me.

Update:

Given the comment that it's for my server's configured time zone, how would I go about determining the current time difference between my server's time zone and some arbitrary timezone, knowing that the value changes throughout the year?

Was it helpful?

Solution

PHP will honor your server's default time zone, so date('I') will always return false in Arizona if your server is correctly configured.

You may temporarily change the default time zone to an area that does observe DST. To change the default time zone use date_default_timezone_set() as indicated here.

OTHER TIPS

Here's how I do it:

// Determine if DST is currently in effect
function isDST(): bool
{
    $server_timezone = date_default_timezone_get();
    // Set the timezone to one we know observes DST because date() uses the server timezone
    date_default_timezone_set('America/New_York');
    $is_dst = date('I');
    // reset server timezone
    date_default_timezone_set($server_timezone);

    return $is_dst;
}

You don't have to change the server timezone and determine if the DST is currently effective. Here is a easy way to do it:

function isDst($timezone) {
    $date = new DateTime('now', new DateTimeZone($timezone));
    return (bool) $date->format('I');
}
// isDst(date_default_timezone_get()) for server timezone
// isDst('America/Los_Angeles')

To determine the time difference between two time zones:

function getTimezoneDiff($tz1, $tz2) {
    $date1 = new DateTime('today', new DateTimeZone($tz1));
    $date2 = new DateTime('today', new DateTimeZone($tz2));

    // Get the difference in seconds
    $secondsDiff = $date2->getTimestamp() - $date1->getTimestamp();

    // Some magic to format the time difference
    $timeDiff = gmdate('H:i:s', abs($secondsDiff));
    return (($secondsDiff > 0) ? '' : '-') . $timeDiff;
}
// getTimezoneDiff('America/Los_Angeles', 'Asia/Kolkata') ==> '-12:30:30'

Note: A negative return value indicates $tz1 is behind $tz2.

If you have lot of date time manipulations in your app you can use the Carbon library, which makes it a breeze to do the date time calculations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top