Search code examples
phpdatetimezonedst

Timezone and Daylight Savings Issues


I've looked through the other solutions on SO and none of them seem to address the timezone/dst issue in the following regard.

I am making calls to NOAA Tide Prediction API and NOAA National Weather Service API which require a time range to be passed for retrieving data. For each location in my database, I have the timezone as a UTC offset and whether daylight savings time is observed (either 1 or 0). I'm trying to format some dates (todays and tomorrow) to be what the LST (Local Standard Time) would be in it's own timezone so I can pass to these API's.

I'm having trouble figuring out how to know if a date, such as todays, is within the daylight savings time range or not.

Here is what I have so far:

// Get name of timezone for tide station
// NOTE: $locationdata->timezone is something like "-5"
$tz_name = timezone_name_from_abbr("", $locationdata->timezone * 3600, false);
$dtz = new DateTimeZone($tz_name);    

// Create time range
$start_time = new DateTime('', $dtz);
$end_time = new DateTime('', $dtz);
$end_time = $end_time->modify('+1 day');

// Modify time to match local timezone
$start_time->setTimezone($dtz);
$end_time->setTimezone($dtz);

// Adjust for daylight savings time
if( $locationdata->dst == '1' )
{
   // DST is observed in this area. 

   // ** HOW DO I KNOW IF TODAY IS CURRENTLY DST OR NOT? **  

}           

// Make call to API using modified time range
...

How can I go about doing this? Thanks.


Solution

  • You can use PHP's time and date functions:

    $tzObj = timezone_open($tz_name);
    $dateObj = date_create("07.03.2012 10:10:10", $tzObj);
    
    $dst_active = date_format($dateObj, "I");
    

    If DST is active on the given date, $dst_active is 1, else 0.

    Instead of specifying a time in the call to date_create you can also pass "now" to receive the value for the current date and time.

    However, like Jon mentioned, different countries within the same timezone offset may observe DST while others may not.