<?
date_default_timezone_set("GMT");
function scheme() {
$sunrise = date_sunrise(time(), SUNFUNCS_RET_DOUBLE, $latitude, $longitude, 96, 0);
$sunset = date_sunset(time(), SUNFUNCS_RET_DOUBLE, $latitude, $longitude, 96, 0);
$now = date("H") + date("i") / 60 + date("s") / 3600;
if ($sunrise < $sunset)
if (($now > $sunrise) && ($now < $sunset)) return "day";
else return "night";
else
if (($now > $sunrise) || ($now < $sunset)) return "day";
else return "night";
}
?>
Refactorings
No refactoring yet !
Ants
November 2, 2009, November 02, 2009 20:47, permalink
I don't understand the logic in lines 13-14. It looks like that in lines 10-11, now must strictly be between sunrise and sunset for it to be daytime, but for lines 13-14 now can be after sunrise OR before sunset and it's safe to call it day time. I suspect a set of typo's there, or that you mean to use 'xor' instead of '||'.
As a warning, I don't do PHP, but here would be my first stab looking at the man pages:
<?
date_default_timezone_set("GMT");
function scheme() {
$now = time();
$zenith = 96;
$offset = 0;
return (($now > date_sunrise($now, SUNFUNCS_RET_TIMESTAMP, $latitude, $longitude, $zenith, $offset)) &&
($now < date_sunset($now, SUNFUNCS_RET_TIMESTAMP, $latitude, $longitude, $zenith, $offset)))
? "day" : "night";
}
?>
<?
date_default_timezone_set("GMT");
function scheme() {
$now = time();
$zenith = 96;
$offset = 0;
$sunrise = date_sunrise($now, SUNFUNCS_RET_TIMESTAMP, $latitude, $longitude, $zenith, $offset);
$sunset = date_sunset($now, SUNFUNCS_RET_TIMESTAMP, $latitude, $longitude, $zenith, $offset);
$isDay = ($sunrise < $now) && ($now < $sunset);
if ($sunrise > $sunset)
$isDay = !$isDay;
return $isDay ? "day" : "night";
}
?>
Ben Marini
November 3, 2009, November 03, 2009 03:10, permalink
First off, your $latitude and $longitude are not defined, so no point in including those. Seemed like most of the params you were passing to date_sunrise() and date_sunset() were or could be handled by defaulting values in the ini or via ini_set(), unless you needed them to be variable. As for the if/else logic, just say it out loud and it makes perfect sense. "If the current time is after the sunrise and before the sunset, then it's daytime. Otherwise, it's nightime". I thought it made more sense for this function to return a boolean, to give it more reusability. Oh yeah, and using a timestamp as a return value for date_sunrise/set() makes it a lot easier to do comparisons with the current time.
<?php
date_default_timezone_set("GMT");
// Returns true if it is daytime, false otherwise
function daytime() {
$now = time();
$sunrise = date_sunrise($now, SUNFUNCS_RET_TIMESTAMP);
$sunset = date_sunset( $now, SUNFUNCS_RET_TIMESTAMP);
return ($sunrise < $now && $now < $sunset);
}
echo daytime() ? "day" : "night";
I'm using the built-in date_sunset and date_sunrise, but the logic here just feels dumb, like it could be done in one line and I'm just not seeing it.