Reputation: 101
I am having trouble finding a way to display a time accounting for daylight savings changes. This script is supposed to return the time for Dusk on any specified date at a specific place in the Eastern time zone. It works, but, it doesn't give the correct time in the winter (it's off by an hour). I've tried a variety of ways to deal with it, but nothing seems to work. I thought that simply setting the timezone to NY would do it, but it's still wrong. Help?
<?php
$setdate = htmlspecialchars($_GET["date"]);
$the_date = strtotime($setdate);
$returned_date = date_sunset($the_date, SUNFUNCS_RET_STRING, 35.7786, -78.63, 96, 0);
$date = new DateTime($returned_date, new DateTimeZone('GMT'));
$date->setTimezone(new DateTimeZone('America/New_York'));
echo $date->format('h:i ');
?>
Upvotes: 1
Views: 79
Reputation: 32232
date_sunset()
with SUNFUNCS_RET_STRING
returns only the time portion, eg: 22:51
so when you feed only that into the DateTime constructor it assumes that you want all the rest of the details filled in with the current values. So you're applying some other date's sunset to today's TZ values with differing DST, eg: UTC-4 vs UTC-5.
I would suggest using SUNFUNCS_RET_TIMESTAMP
, an also going all-in with the DateTime library.
$utc = new DateTimezone('UTC');
$nyc = new DateTimezone('America/New_York');
$date_str = '2021-12-25';
// parse the date string _explicitly_, do not rely on the library's _guess_ at the format.
$date = DateTime::createFromFormat('Y-m-d H:i:s', $date_str . ' 00:00:00', $utc);
// return the timestamp instead of the string
$sunset_stamp = date_sunset($date->format('U'), SUNFUNCS_RET_TIMESTAMP, 35.7786, -78.63, 96, 0);
$sunset = (new DateTime('', $nyc))->setTimestamp($sunset_stamp);
var_dump($sunset->format('c'));
Output:
string(25) "2021-12-25T17:36:51-05:00"
Upvotes: 1