Moon’s Lunar Phase in JavaScript

Photo by Mathew Schwartz on Unsplash

Using Julian date, you can calculate the current phase of the moon by finding the lunar age as a percentage through the lunar month.

In lunar calendars, a lunar month is the time between two identical syzygies. This is the equivalent of 29.53059 Earth days.

Start by obtaining Julian date:

With Julian date, calculate days or percentage through the lunar month:

Using the percentage through the lunar month, you can determine the current phase and precise position of shadow.

Lunar phases in order are as follows:

  • 🌑 New
  • 🌘 Waning Crescent
  • 🌗 Last Quarter
  • 🌖 Waning Gibbous
  • 🌕 Full
  • 🌔 Waxing Gibbous
  • 🌓 First Quarter
  • 🌒 Waxing Crescent

Apply these to percentage ranges to get the phase:

Or, use lunar age to determine whether the moon is waning or waxing:

This code has been assembled into a library in my lunarphase-js GitHub project, or install via npm:

Then, import and use as:

API is as follows:

  • getLunarPhase() — Get the current lunar phase from the LunarPhase enum (ex: "Full")
  • getLunarPhaseEmoji() —Get the current lunar phase emoji from the LunarPhaseEmoji enum (ex: "🌕")
  • getLunarAge() — Get the lunar age (ex: 16.54412413414952)
  • getLunarAgePercent() — Get the percentage through the lunar cycle (ex: 0.5602368519132597)
  • isWaxing() — Whether the moon is waxing (ex: false)
  • isWaning() — Whether the moon is waning (ex: true)
  • getJulianDate()— Get the current Julian date (ex: 2459244.5972259142)

Avant-garde experimental artist — creative professional leveraging technology for immersive experiences

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store