JavaScript Sun/Moon Position & Phase Calculator – SunCalc

Category: Javascript , Recommended | June 23, 2026
Authormourner
Last UpdateJune 23, 2026
LicenseMIT
Tags
Views0 views
JavaScript Sun/Moon Position & Phase Calculator – SunCalc

SunCalc is a tiny, dependency-free JavaScript library that calculates sun position, sunlight phases (sunrise, sunset, twilight), moon position, moon illumination, and moonrise/moonset times for any location and date.

It uses high‑precision astronomical formulas from Jean Meeus’ Astronomical Algorithm and matches the accuracy of timeanddate.com and the U.S. Naval Observatory.

The library can help you add reliable solar and lunar data to dashboards, photography planners, outdoor activity widgets, or any app that needs location‑aware sun/moon information.

You can retrieve a full set of solar event times with a single function call and get instant moon illumination values without external APIs.

Features:

  • Calculates Sun altitude and compass azimuth in degrees.
  • Returns sunrise, sunset, dawn, dusk, and golden-hour times.
  • Supports astronomical, nautical, and civil twilight phases.
  • Custom solar altitude thresholds for light windows.
  • Returns Moon altitude, azimuth, distance, and parallactic angle.
  • Calculates lunar illumination, phase, bright-limb angle, and waxing state.
  • Finds moonrise and moonset times for a selected day.
  • Reports polar-day and polar-night conditions through status flags.

Use Cases:

  • Photography planners highlight golden hour and blue hour for a chosen destination.
  • Outdoor booking calendars display daylight windows for tours, hikes, and events.
  • Map scenes rotate directional lighting from the Sun’s current azimuth and altitude.
  • Stargazing dashboards show lunar phase, illumination percentage, moonrise, and moonset data.

How To Use It

Installation

Install SunCalc with npm:

npm install suncalc

Import the full API into an ES module:

import * as SunCalc from 'suncalc';

A browser-ready module build is also available through jsDelivr:

<script type="module">
  import * as SunCalc from 'https://cdn.jsdelivr.net/npm/suncalc/+esm';
</script>

The browser bundle exposes a global SunCalc object:

<script src="https://cdn.jsdelivr.net/npm/suncalc"></script>

Basic Usage

Get the main sunlight times for a location, then format the returned Date objects for the intended time zone.

import * as SunCalc from 'suncalc';
const latitude = 34.0522;
const longitude = -118.2437;
const selectedDate = new Date();
const solarTimes = SunCalc.getTimes(selectedDate, latitude, longitude);
const formatter = new Intl.DateTimeFormat('en-US', {
  timeZone: 'America/Los_Angeles',
  hour: 'numeric',
  minute: '2-digit'
});
if (solarTimes.sunset) {
  console.log(`Sunset: ${formatter.format(solarTimes.sunset)}`);
}
console.log(`Solar noon: ${formatter.format(solarTimes.solarNoon)}`);

Advanced Usages

Display the Sun’s Direction

const sun = SunCalc.getPosition(
  new Date('2026-07-16T18:00:00Z'),
  40.7128,
  -74.006
);
console.log(`Sun altitude: ${sun.altitude.toFixed(2)}°`);
console.log(`Sun azimuth: ${sun.azimuth.toFixed(2)}°`);

SunCalc measures azimuth clockwise from north. An azimuth of 90 points east, while 180 points south.

Add Blue-Hour Times

SunCalc.addTime(-4, 'morningBlueHourEnd', 'blueHourStart');
SunCalc.addTime(-8, 'morningBlueHourStart', 'blueHourEnd');
const times = SunCalc.getTimes(
  new Date(),
  47.6062,
  -122.3321
);
console.log(times.morningBlueHourStart);
console.log(times.blueHourEnd);

addTime() updates the shared SunCalc.times list. Register custom times once during application startup.

Build a Moon Phase Label

const phaseNames = [
  'New Moon',
  'Waxing Crescent',
  'First Quarter',
  'Waxing Gibbous',
  'Full Moon',
  'Waning Gibbous',
  'Last Quarter',
  'Waning Crescent'
];
const moon = SunCalc.getMoonIllumination(new Date());
const phaseName = phaseNames[Math.round(moon.phase * 8) % 8];
const illumination = Math.round(moon.fraction * 100);
console.log(`${phaseName}: ${illumination}% illuminated`);

Do not compare fraction directly against 0 or 1. Exact new-moon and full-moon illumination values occur only under eclipse conditions.

Show Moonrise and Moonset

const moonTimes = SunCalc.getMoonTimes(
  new Date(),
  35.6895,
 139.6917
);
if (moonTimes.rise) {
  console.log(`Moonrise: ${moonTimes.rise.toISOString()}`);
}
if (moonTimes.set) {
  console.log(`Moonset: ${moonTimes.set.toISOString()}`);
}

The Moon may rise or set zero, one, or two times during the selected day.

API Methods

// Return refraction-corrected Sun altitude and compass azimuth in degrees.
SunCalc.getPosition(date, latitude, longitude);
// Return solar events such as sunrise, sunset, dawn, dusk, golden hour, solar noon, and nadir.
SunCalc.getTimes(date, latitude, longitude, observerHeight);
// Add custom ascending and descending Sun altitude crossings.
SunCalc.addTime(angleInDegrees, morningName, eveningName);
// Return Moon altitude, azimuth, distance in kilometers, and parallactic angle.
SunCalc.getMoonPosition(date, latitude, longitude);
// Return Moon illumination fraction, phase, bright-limb angle, and waxing state.
SunCalc.getMoonIllumination(date);
// Return Moon rise and set times for the selected UTC day.
SunCalc.getMoonTimes(date, latitude, longitude);
// Read registered solar event definitions.
SunCalc.times;

FAQs:

Q: Does SunCalc require an API key?
A: No. SunCalc runs calculations locally from the selected date, latitude, and longitude. Your application must provide the location data.

Q: Does SunCalc return local times?
A: SunCalc returns JavaScript Date objects that represent absolute instants. Format them through Intl.DateTimeFormat with an explicit timeZone for reliable local display.

Q: Why is sunrise or sunset equal to null?
A: The Sun may remain above or below the relevant altitude for an entire day at high latitudes. Check the alwaysUp and alwaysDown flags before rendering a fallback message.

Q: Does SunCalc generate a weather widget or calendar UI?
A: No. SunCalc handles astronomical calculations only. Pair it with your own HTML, CSS, charts, maps, date picker, or dashboard components.

You Might Be Interested In:


Leave a Reply