Skip to content

Instantly share code, notes, and snippets.

@bramus
Last active November 27, 2018 13:23
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bramus/880d4204f94918e9c9250f214cf0c607 to your computer and use it in GitHub Desktop.
Save bramus/880d4204f94918e9c9250f214cf0c607 to your computer and use it in GitHub Desktop.
PHP: Is The Sun Up (standalone version)?
<?php
function sunIsUp(\DateTime $when, $lat, $lon): bool {
$whenTimestamp = $when->getTimestamp();
$sunriseTimestamp = date_sunrise(
$whenTimestamp,
SUNFUNCS_RET_TIMESTAMP,
$lat,
$lon
);
$sunsetTimestamp = date_sunset(
$whenTimestamp,
SUNFUNCS_RET_TIMESTAMP,
$lat,
$lon
);
return ($whenTimestamp > $sunriseTimestamp) && ($whenTimestamp < $sunsetTimestamp);
}
<?php
// Verify sunIsUp 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;
var_dump(sunIsUp(new \DateTime('2018-11-15 07:15:00', new \DateTimeZone('Europe/Brussels')), $lat, $lon)); // false
var_dump(sunIsUp(new \DateTime('2018-11-15 07:59:00', new \DateTimeZone('Europe/Brussels')), $lat, $lon)); // false
var_dump(sunIsUp(new \DateTime('2018-11-15 08:00:00', new \DateTimeZone('Europe/Brussels')), $lat, $lon)); // true
var_dump(sunIsUp(new \DateTime('2018-11-15 09:15:00', new \DateTimeZone('Europe/Brussels')), $lat, $lon)); // true
var_dump(sunIsUp(new \DateTime('2018-11-15 16:15:00', new \DateTimeZone('Europe/Brussels')), $lat, $lon)); // true
var_dump(sunIsUp(new \DateTime('2018-11-15 16:55:00', new \DateTimeZone('Europe/Brussels')), $lat, $lon)); // true
var_dump(sunIsUp(new \DateTime('2018-11-15 16:56:00', new \DateTimeZone('Europe/Brussels')), $lat, $lon)); // false
var_dump(sunIsUp(new \DateTime('2018-11-15 17:15:00', new \DateTimeZone('Europe/Brussels')), $lat, $lon)); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment