Fun question. I wanted to give it a try and come up with something totally different than what was proposed so far. This is what I got:
function isDay() {
return (Date.now() + 60000 * new Date().getTimezoneOffset() + 21600000) % 86400000 / 3600000 > 12;
}
It will return true if it's between 6 AM and 6 PM, or false otherwise.
Breaking down into parts:
Date.now()
returns UTC epoch in milliseconds;
new Date().getTimezoneOffset()
gets local time zone, in minutes, and 60000
just converts it to milliseconds;
- 21600000 represents 6 hours in milliseconds. This is a hack to pretend each day starts at 6 AM (will be explained in the end);
- 86400000 is how many milliseconds there is in a day, so
X % 86400000
will return how many milliseconds have passed since the current day begun; since we added 6 hours in the previous step, this is actually counting millis since 6 AM;
- we divide that result by 3600000 (number of milliseconds in an hour) to find out how many hours have passed since the day begun;
- since we added 6 hours to our clock, 6 AM is now 12 PM, and 6 PM is actually midnight. This is why the function checks to see if the value is greater than 12; if it is, it must be between 6 AM and 6 PM right now. Anything earlier than 6 AM or later than 6 PM becomes less than 12, according to that formula.
Of course, the same can be accomplished with:
function isDay() {
const hours = (new Date()).getHours();
return (hours >= 6 && hours < 18);
}
But that is not even half as fun :-D