Search code examples
phpdatetimedst

In PHP, how to get UTC date for calendars that include Day Light Savings (DLS)


I'm not sure if the gmdate() function in PHP captures the Day Light Savings reality of the world. For example this code:

<?php 

echo "<pre>";

echo "Current timezone: ", date_default_timezone_get(), "\n"; 
$future_date = 'Nov 03, 2019  03:30 PM EDT';
$future_UTC  = gmdate('M d, Y  h:i A T', strtotime($future_date));

echo "
New York Date: $future_date 
GMT/UTC time:  $future_UTC
"; 

?>

Prints out this:

Current timezone: UTC

  New York Date: Nov 03, 2019  03:30 PM EDT 
  GMT/UTC time:  Nov 03, 2019  07:30 PM GMT

This is technically incorrect, because on Nov 3 at 2pm, the DLS will switch and the time in GMT/UTC will actually be 08:30 PM, instead of the erroneous 07:30 PM that PHP is showing (based on today's DLS).

Is there any way to automatically get the right time for future dates?


Solution

  • There are many errors here, starting with the title of your question:

    how to get UTC date for calendars that include Day Light Savings (DLS)

    UTC is well-defined, and has no daylight savings time. If you're in a different timezone, and in a locality that has daylight savings time, then you're not in UTC anymore. So, the question is nonsensical to begin with.

    $future_date = 'Nov 03, 2019  03:30 PM EDT';
    

    EDT means "Eastern Daylight Time", so in this case you're forcing a particular interpretation, regardless of date. You'll note that if you change it to EST (Eastern Standard Time), you'll get a different result.

    You probably want America/New_York instead of EDT. See also: https://www.php.net/manual/en/timezones.php

    This is technically incorrect, because on Nov 3 at 2pm, the DLS will switch

    No. 2:00 AM.

    Is there any way to automatically get the right time for future dates?

    Stop feeding PHP broken data and ambiguously formatted dates. We have date/time standards for a reason, such as ISO8601. Date/time is a complicated thing. Computers can't read minds, and don't know what you intended when you gave it the wrong date for a specific type of timezone with daylight savings time.