Skip to content

Instantly share code, notes, and snippets.

@codyphobe
Forked from bramus/isSunSup.php
Last active February 28, 2020 22:41
Show Gist options
  • Save codyphobe/be32f497e94d08b788047807dfc2db04 to your computer and use it in GitHub Desktop.
Save codyphobe/be32f497e94d08b788047807dfc2db04 to your computer and use it in GitHub Desktop.
A standalone PHP function to check whether or not the Sun is above the horizon in a given location and time
<?php
function isSunUp(\DateTime $when, $lat, $lon): bool
{
$whenTimestamp = $when->getTimestamp();
[$sunriseTimestamp, $sunsetTimestamp] = array_map(function ($f) use ($whenTimestamp, $lat, $lon) {
return $f($whenTimestamp, SUNFUNCS_RET_TIMESTAMP, $lat, $lon);
}, ['date_sunrise', 'date_sunset']);
return ($whenTimestamp > $sunriseTimestamp) && ($whenTimestamp < $sunsetTimestamp);
}
// Verify isSunUp functionality using location of Brussels, Belgium.
// On 2018-11-15, sunrise should be at 08:00 and sunset at 16:56
$lat = 50.8503;
$lon = 4.3517;
$tz = new \DateTimeZone('Europe/Brussels');
var_dump(isSunUp(new \DateTime('2018-11-15 07:15:00', $tz), $lat, $lon)); // false
var_dump(isSunUp(new \DateTime('2018-11-15 07:59:00', $tz), $lat, $lon)); // false
var_dump(isSunUp(new \DateTime('2018-11-15 08:00:00', $tz), $lat, $lon)); // true
var_dump(isSunUp(new \DateTime('2018-11-15 09:15:00', $tz), $lat, $lon)); // true
var_dump(isSunUp(new \DateTime('2018-11-15 16:15:00', $tz), $lat, $lon)); // true
var_dump(isSunUp(new \DateTime('2018-11-15 16:55:00', $tz), $lat, $lon)); // true
var_dump(isSunUp(new \DateTime('2018-11-15 16:56:00', $tz), $lat, $lon)); // false
var_dump(isSunUp(new \DateTime('2018-11-15 17:15:00', $tz), $lat, $lon)); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment