Created
September 17, 2016 10:07
-
-
Save Dither/d2801f7b22d5602fff38821c2177e301 to your computer and use it in GitHub Desktop.
JS function to calculate moon phase
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function moon_phase(date) { // ported from http://www.voidware.com/moon_phase.htm | |
var year = date.getYear(), | |
month = date.getMonth(), | |
day = date.getDay(); | |
if (month < 3) { | |
year--; | |
month += 12; | |
} | |
++month; | |
jd = 365.25 * year + 30.6 * month + day - 694039.09; // jd is total days elapsed | |
jd /= 29.53; // divide by the moon cycle (29.53 days) | |
phase = parseInt(jd, 10); // int(jd) -> phase, take integer part of jd | |
jd -= phase; // subtract integer part to leave fractional part of original jd | |
phase = Math.ceil(jd * 8); // scale fraction from 0-8 and round by adding 0.5 | |
phase = phase & 7; // 0 and 8 are the same so turn 8 into 0 | |
switch (phase) { | |
case 0: phase = "New Moon"; break; | |
case 1: phase = "Waxing Crescent Moon"; break; | |
case 2: phase = "Quarter Moon"; break; | |
case 3: phase = "Waxing Gibbous Moon"; break; | |
case 4: phase = "Full Moon"; break; | |
case 5: phase = "Waning Gibbous Moon"; break; | |
case 6: phase = "Last Quarter Moon"; | |
case 7: phase = "Waning Crescent Moon"; break; | |
} | |
return phase; | |
} | |
//document.write(moon_phase(new Date(Date.now()))) |
Worked amazingly. Thanks so much.
This seems to be bugging out on me.
function moonphase() {
var date = new Date(Date.now());
var year = date.getYear();
var month = date.getMonth();
var day = date.getDay();
...
return phase + " - "+year+"/"+month+"/"+day;
}
moonphase() returns:
"3 - Quarter Moon - 121/9/1"
Today, which is 20th Sept 2021 - and almost a full moon.
Any ideas? Is it a date parsing or index issue?
Right, the problem is the methods are either wrong/old or have changed since this was first written.
They need to be changed to
var year = date.getFullYear();
var month = date.getMonth(); //index 0-11 check
var day = date.getDate();
Today 27/09/2021 it returns:
8 - Waning Crescent Moon
when it is actually a Waning Gibbous.
There should be a break
after the sixth case; this will never return 'Last Quarter Moon'.
Doesn't work for me
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you 😃