Reputation: 14324
PHP allows me to quickly check the sunrise and sunset times for any day at a specific Latitude & Longitude.
Is there a simple way to calculate which day is the Solstice? By which I mean - at my specific location, which day has the most hours of sunlight and which has the least?
Upvotes: 1
Views: 1655
Reputation: 31
The above code uses functions that will be depreciated in PHP 8.1 and, depending on system configuration, could lead to memory exhaustion. I took the liberty to rewrite the function so it's compatible with PHP 8.
We know for fact that solstices occur between the 20th and the 23rd of June and December. With this in mind, we are able to zero in on those two specific months and those four specific days.
function solstice() {
$delta = $dates = array();
$year = date('Y', time());
$months = array(6,12);
$days = array(19,20,21,22,23,24);
$latitude = 31.47;
$longitude = 35.13;
$dateFormat = 'l, d F Y';
foreach ($months AS $month) {
foreach ($days AS $day) {
$date = sprintf('%d-%02d-%d', $year, $month, $day);
$solar = date_sun_info(strtotime($date), $latitude, $longitude);
$delta[] = ($solar['sunset'] - $solar['sunrise']);
$dates[] = $date;
unset($solar);
}
}
print('<pre>');
print_r($delta);
print_r($dates);
print('</pre>');
$shortest_key = array_search(min($delta), $delta);
$longest_key = array_search(max($delta), $delta);
printf(_('The longest day is: %s<br />'), date($dateFormat, strtotime($dates[$longest_key])));
printf(_('The shortest day is: %s'), date($dateFormat, strtotime($dates[$shortest_key])));
}
Thanks to @MorKadosh for seeding the basic idea.
Upvotes: 3
Reputation: 6006
I wouldn't call it "simple", but I thought about calculating the time differences between the sunrise and sunset in each day, then storing this data in an array, and finally finding the min/max value. Iv'e made something really quick, hope it would be useful:
(I used random long/lat)
function solstice() {
// Set timezone
date_default_timezone_set('UTC');
$date='2014/01/01';
$end_date='2014/12/31';
$i = 0;
//loop through the year
while(strtotime($date)<=strtotime($end_date)) {
$sunrise=date_sunrise(strtotime($date),SUNFUNCS_RET_DOUBLE,31.47,35.13,90,3);
$sunset=date_sunset(strtotime($date),SUNFUNCS_RET_DOUBLE,31.47,35.13,90,3);
//calculate time difference
$delta = $sunset-$sunrise;
//store the time difference
$delta_array[$i] = $delta;
//store the date
$dates_array[$i] = $date;
$i++;
//next day
$date=date("Y-m-d",strtotime("+1 day",strtotime($date)));
}
$shortest_key = array_search(min($delta_array), $delta_array);
$longest_key = array_search(max($delta_array), $delta_array);
echo "The longest day is:".$dates_array[$longest_key]. "<br />";
echo "The shortest day is:".$dates_array[$shortest_key]. "<br />";
}
Upvotes: 3