The terminal on this site answers mars, moon, planets and ping mars with live numbers, and none of those commands call an API. Everything comes from the system clock and one small file of textbook formulas, src/lib/astro.ts. This post walks through that file, then does the part most "astronomy in JavaScript" snippets skip: checking the output against real events and being honest about where it misses and why.
TL;DR
- Convert every timestamp to a Julian Date first. Every formula here is "days since some fixed instant".
- JPL's approximate Keplerian elements, plus two or three Newton iterations on Kepler's equation, put Earth, Mars and Jupiter where they belong. Against real events, Mars and Earth distances land within about a thousandth of an AU.
- A Moon phase from the mean synodic month is good to roughly half a day. Fine for a terminal, not for planning a photo.
- Coordinated Mars Time is one linear formula on the Julian Date, once you convert UTC to Terrestrial Time.
- Write the verification script. Mine found a formatting bug that printed
19 min 60 s.
Start with a Julian Date
Astronomical formulas don't want years, months and time zones. They want one number that counts steadily. The Julian Date (JD) is a continuous count of days, and the Unix epoch (1970-01-01 00:00 UTC) sits at JD 2440587.5. Date.getTime() already gives milliseconds since that epoch, so the conversion is one line:
export const AU_KM = 149_597_870.7;
export const C_KM_S = 299_792.458;
const DEG = Math.PI / 180;
/** Julian Date (UTC) for a JS Date. */
export const julianDate = (d: Date) => d.getTime() / 86_400_000 + 2_440_587.5;The .5 exists because Julian days start at noon. Sanity check: noon UTC on 1 January 2000 should give a round number (J2000.0 itself is noon TT, about a minute earlier in UTC), and julianDate(new Date("2000-01-01T12:00:00Z")) does return 2451545.
Strictly, the planetary elements below expect a dynamical timescale rather than UTC. The gap is about 69 seconds, in which Earth moves less than a thousandth of a degree, so for planets we ignore it. For the Mars clock we won't.
Planet positions from orbital elements
JPL's approximate elements
JPL publishes a short table of Keplerian elements for the major planets, prepared by E. M. Standish, intended for approximate positions between roughly 1800 and 2050. There is a second, longer-range table that needs extra correction terms for the outer planets; the 1800-2050 one doesn't. Each element is given as a value at J2000 plus a linear rate per Julian century (36,525 days). The site keeps four of them per planet: semi-major axis a, eccentricity e, mean longitude L and longitude of perihelion w (written ϖ in most texts).
// a (AU), then [value at J2000, change per Julian century] for
// e (eccentricity), L (mean longitude, deg) and w (longitude of perihelion, deg)
type Elements = { a: number; e: [number, number]; L: [number, number]; w: [number, number] };
const ELEMENTS = {
earth: { a: 1.00000261, e: [0.01671123, -0.00004392], L: [100.46457166, 35999.37244981], w: [102.93768193, 0.32327364] },
mars: { a: 1.52371034, e: [0.0933941, 0.00007882], L: [-4.55343205, 19140.30268499], w: [-23.94362959, 0.44441088] },
jupiter: { a: 5.202887, e: [0.04838624, -0.00013253], L: [34.39644051, 3034.74612775], w: [14.72847983, 0.21252668] },
} satisfies Record<string, Elements>;
export type Planet = keyof typeof ELEMENTS;Three simplifications are baked in. The rate for a is dropped (around a ten-thousandth of an AU per century at most for these planets). Inclination and the ascending node are left out, justified below. And JPL's row used for earth is really the Earth-Moon barycentre, which comes back in the verification section.
Mean anomaly and Kepler's equation
The mean anomaly M = L - w is where the planet would be if it went round its orbit at constant speed. Real planets speed up near the Sun, so we need the eccentric anomaly E, which is tied to M by Kepler's equation, M = E - e·sin E. There is no closed-form solution, but Newton's method on f(E) = E - e·sin E - M, with derivative 1 - e·cos E, converges absurdly fast for small eccentricities. Here it is in isolation with a Mars-like orbit:
const e = 0.0934; // roughly Mars
const M = 2.0; // mean anomaly, radians
let E = M + e * Math.sin(M);
for (let i = 1; i <= 4; i++) {
E -= (E - e * Math.sin(E) - M) / (1 - e * Math.cos(E));
console.log(i, E.toFixed(15), (E - e * Math.sin(E) - M).toExponential(2));
}1 2.081483469838866 4.83e-7
2 2.081483008048217 8.88e-15
3 2.081483008048208 4.44e-16
4 2.081483008048208 -2.22e-16The residual hits floating-point noise by the second iteration. The site runs a fixed eight, which is generous but costs nothing. For high-eccentricity orbits like comets you would want a better starting guess and a real convergence test instead of a fixed count.
From the orbit to ecliptic x and y
With E in hand, the position in the orbit's own frame (Sun at one focus, x axis pointing at perihelion) is a(cos E - e) and a·√(1 - e²)·sin E. Rotating by the longitude of perihelion turns that into heliocentric ecliptic coordinates:
/** Heliocentric ecliptic x, y in AU (inclination ignored: under 2 degrees for these planets). */
export function helio(planet: Planet, d = new Date()): [number, number] {
const el = ELEMENTS[planet];
const T = (julianDate(d) - 2_451_545.0) / 36_525; // Julian centuries since J2000.0
const e = el.e[0] + el.e[1] * T;
const L = el.L[0] + el.L[1] * T;
const w = el.w[0] + el.w[1] * T;
// Mean anomaly, wrapped into [-180, 180) degrees, then radians
const M = ((((L - w) % 360) + 540) % 360 - 180) * DEG;
// Kepler's equation M = E - e sin E, solved with Newton's method
let E = M + e * Math.sin(M);
for (let i = 0; i < 8; i++) E -= (E - e * Math.sin(E) - M) / (1 - e * Math.cos(E));
// Position in the orbit's own frame (x towards perihelion)
const xp = el.a * (Math.cos(E) - e);
const yp = el.a * Math.sqrt(1 - e * e) * Math.sin(E);
// Rotate by the longitude of perihelion into ecliptic coordinates
const c = Math.cos(w * DEG), s = Math.sin(w * DEG);
return [xp * c - yp * s, xp * s + yp * c];
}The odd-looking ((x % 360) + 540) % 360 - 180 wrap is there because L grows by thousands of degrees per century and JavaScript's % keeps the sign of the left operand. Sine and cosine wouldn't care, but small angles are far easier to debug.
Why ignoring inclination is acceptable
The ecliptic is defined by Earth's orbit, so Earth's inclination is essentially zero. Mars's orbit is tilted about 1.85° and Jupiter's about 1.30°, which lifts Mars at most around 0.05 AU off the ecliptic. That offset sits roughly perpendicular to the Earth-Mars line, so it changes the distance by roughly z² / 2d: a few thousandths of an AU at worst. And laying the orbit flat keeps its full radius, which partly cancels the dropped height, so the measured gap is smaller still. Across 2020-2029, the largest gap between this 2D version and a full 3D one was 0.0012 AU for Mars and 0.0003 AU for Jupiter. The 3D version is further down.
Distance and light-time
Once both planets have coordinates, distance is a subtraction and a Math.hypot:
/** Distance between Earth and a planet, in AU. */
export function distanceFromEarth(planet: Exclude<Planet, "earth">, d = new Date()) {
const [ex, ey] = helio("earth", d);
const [px, py] = helio(planet, d);
return Math.hypot(px - ex, py - ey);
}
/** Earth-Sun distance, in AU. */
export const sunDistance = (d = new Date()) => Math.hypot(...helio("earth", d));This is the geometric distance right now, not corrected for where the planet was when its light left, which is the right number for ping mars. Light-time is distance divided by the speed of light, plus formatting, corrected here:
export function lightTime(km: number) {
const s = km / C_KM_S;
if (s > 365.25 * 86_400) return `${(s / (365.25 * 86_400)).toFixed(2)} years`;
if (s > 2 * 86_400) return `${(s / 86_400).toFixed(1)} days`;
if (s < 59.995) return `${s.toFixed(2)} s`; // toFixed(2) would turn 59.996 into "60.00"
const secs = Math.round(s); // round once, then split
if (secs < 3600) return `${Math.floor(secs / 60)} min ${secs % 60} s`;
const mins = Math.round(s / 60);
return `${Math.floor(mins / 60)} h ${mins % 60} min`;
}The site's current version floors the minutes and rounds the leftover seconds separately: Math.floor(s / 60) and Math.round(s % 60). Anything from 59.5 seconds past a minute up to the next minute prints a 60. My verification run hit it at Mars's solar conjunction, 2.4038 AU away:
19 min 60 sThe hour branch can print 1 h 60 min the same way. The fix above rounds once and then splits it, so the same value now prints 20 min 0 s. At closest approach in January 2025, 0.6412 AU, it prints 5 min 20 s.
The Moon's phase from one number
Age, angle and illumination
New moon to new moon averages 29.530588853 days, the mean synodic month. Pick one known new moon, count days since then, take the remainder, and you have the Moon's age:
const SYNODIC = 29.530588853; // mean synodic month, days
const KNOWN_NEW_MOON = 2_451_550.1; // JD of the reference new moon used by the site
export function moonPhase(d = new Date()) {
const age = (((julianDate(d) - KNOWN_NEW_MOON) % SYNODIC) + SYNODIC) % SYNODIC;
const angle = (age / SYNODIC) * 2 * Math.PI;
const illumination = (1 - Math.cos(angle)) / 2;
const names = ["New Moon", "Waxing Crescent", "First Quarter", "Waxing Gibbous",
"Full Moon", "Waning Gibbous", "Last Quarter", "Waning Crescent"];
const name = names[Math.floor((age / SYNODIC) * 8 + 0.5) % 8];
return { age, angle, illumination, name };
}The double modulo keeps dates before 2000 positive. angle treats the Moon's angular distance from the Sun as growing uniformly through the month, and the lit fraction follows as (1 - cos angle) / 2: 0 at new, one half at the quarters, 1 at full. Each of the eight names covers an eighth of the cycle, about 3.7 days, and the + 0.5 centres each slot on its moment, so "Full Moon" is reported for nearly two days either side.
Why it can be half a day off
The real Moon doesn't move uniformly. Its orbit is noticeably elliptical and Earth's speed around the Sun varies too, so individual lunations run from roughly 29.3 to 29.8 days. Actual phases therefore wander around the mean schedule by up to about half a day, a little more in the worst cases. A mean-month model cannot see any of that. If you need the hour of a full moon, use the phase algorithm with periodic correction terms from Jean Meeus's Astronomical Algorithms, or an ephemeris.
Drawing the Moon in ASCII
The moon command also draws the disc:
/** ASCII disc of the Moon as seen from the northern hemisphere. */
export function moonArt(angle: number, rows = 9) {
const cols = rows * 2; // terminal cells are roughly twice as tall as they are wide
const out: string[] = [];
for (let r = 0; r < rows; r++) {
let line = "";
const y = ((r + 0.5) / rows) * 2 - 1;
for (let c = 0; c < cols; c++) {
const x = ((c + 0.5) / cols) * 2 - 1;
const w = Math.sqrt(Math.max(0, 1 - y * y)); // half-width of the disc on this row
if (Math.abs(x) > w) { line += " "; continue; }
const lit = angle <= Math.PI ? x > Math.cos(angle) * w : x < Math.cos(angle - Math.PI) * w;
line += lit ? "@" : "·";
}
out.push(line.replace(/\s+$/, ""));
}
return out.join("\n");
}Each row is a horizontal slice of a unit circle with half-width w. The terminator, the line between day and night, projects onto the disc as half an ellipse, crossing each row at x = cos(angle)·w. While the Moon waxes, everything right of that point is lit; while it wanes, the mirrored test lights the left side. Here is moonArt(2.4), a waxing gibbous:
·@@@@@@@
··@@@@@@@@@@@@
··@@@@@@@@@@@@@@
···@@@@@@@@@@@@@@@
··@@@@@@@@@@@@@@@@
···@@@@@@@@@@@@@@@
··@@@@@@@@@@@@@@
··@@@@@@@@@@@@
·@@@@@@@From the southern hemisphere the Moon appears flipped, so mirror x if that's your audience. The mars command reuses the same function with moonArt(Math.PI, 7), a fully lit disc painted orange.
Coordinated Mars Time
A Mars solar day, a sol, lasts 24 h 39 min 35.244 s, which is 1.0274912517 Earth days. The Mars Sol Date (MSD) counts sols from a fixed epoch, and Coordinated Mars Time (MTC), the fractional part of the MSD as hours, minutes and seconds, is mean solar time at Mars's prime meridian, the Airy-0 crater: Mars's UTC.
/** Mars Sol Date and Coordinated Mars Time (Mars's equivalent of UTC, at the Airy-0 meridian). */
export function marsTime(d = new Date()) {
const jdTT = julianDate(d) + 69.184 / 86_400; // TT = UTC + 37 s (TAI - UTC since 2017) + 32.184 s
const msd = (jdTT - 2_405_522.0028779) / 1.0274912517;
const h = (msd % 1) * 24;
const hh = Math.floor(h), mm = Math.floor((h - hh) * 60), ss = Math.floor(((h - hh) * 60 - mm) * 60);
const pad = (n: number) => String(n).padStart(2, "0");
return { msd, mtc: `${pad(hh)}:${pad(mm)}:${pad(ss)}` };
}The formula wants the Julian Date in Terrestrial Time, not UTC. TT runs 32.184 s ahead of International Atomic Time, which has been 37 s ahead of UTC since the start of 2017, so TT = UTC + 69.184 s. If another leap second is ever added, that constant has to change. Skip the conversion and the Mars clock runs about a minute behind. For example, marsTime(new Date("2025-12-05T00:00:00Z")) returns { msd: 54007.75707922359, mtc: '18:10:11' }.
I checked three things. 1.0274912517 × 86,400 is 88,775.244 seconds, the sol length above. NASA's Mars24 documentation gives the formula in days since J2000; rewritten with JD_TT it is (JD_TT - 2451549.5) / 1.0274912517 + 44796.0 - 0.0009626; the compact form here is the same expression rearranged, and both agree to six decimals. And advancing the clock by exactly one sol advances the MSD by 1.000000. That proves the code matches the published formula; to check the formula itself, compare against Mars24.
Checking the numbers against real events
The verification script
Copying formulas is half the job. The other half is running the real file against dates where the answer is known:
// check-astro.mts: run from the project root with `npx tsx check-astro.mts`
import { resolve } from "node:path";
import { pathToFileURL } from "node:url";
const astro = await import(pathToFileURL(resolve("src/lib/astro.ts")).href);
const { distanceFromEarth, sunDistance, moonPhase, helio } = astro;
type Body = "mars" | "jupiter";
const HOUR = 3_600_000;
const SYNODIC = 29.530588853;
const stamp = (t: number) => new Date(t).toISOString().slice(0, 16).replace("T", " ");
const wrap180 = (deg: number) => (((deg % 360) + 540) % 360) - 180;
/** Hour-by-hour search for the time where f is smallest or largest. */
function argExtreme(f: (d: Date) => number, from: string, to: string, kind: "min" | "max") {
let best = { t: 0, v: kind === "min" ? Infinity : -Infinity };
for (let t = Date.parse(from); t <= Date.parse(to); t += HOUR) {
const v = f(new Date(t));
if (kind === "min" ? v < best.v : v > best.v) best = { t, v };
}
return best;
}
/** Heliocentric longitude of a planet minus Earth's, minus a target angle, wrapped. */
function offset(planet: Body, d: Date, target: number) {
const [ex, ey] = helio("earth", d);
const [px, py] = helio(planet, d);
return wrap180(((Math.atan2(py, px) - Math.atan2(ey, ex)) * 180) / Math.PI - target);
}
function row(label: string, t: number, au?: number) {
console.log(`${label.padEnd(22)}${stamp(t)}${au === undefined ? "" : ` ${au.toFixed(4)} AU`}`);
}
const closest = argExtreme((d) => distanceFromEarth("mars", d), "2024-12-01", "2025-02-28", "min");
row("Mars closest approach", closest.t, closest.v);
const opp = argExtreme((d) => Math.abs(offset("mars", d, 0)), "2024-12-01", "2025-02-28", "min");
row("Mars opposition", opp.t, distanceFromEarth("mars", new Date(opp.t)));
const conj = argExtreme((d) => Math.abs(offset("mars", d, 180)), "2025-11-01", "2026-03-01", "min");
row("Mars conjunction", conj.t, distanceFromEarth("mars", new Date(conj.t)));
const jup = argExtreme((d) => Math.abs(offset("jupiter", d, 0)), "2024-11-01", "2025-01-31", "min");
row("Jupiter opposition", jup.t, distanceFromEarth("jupiter", new Date(jup.t)));
const peri = argExtreme(sunDistance, "2024-12-20", "2025-01-20", "min");
row("Earth perihelion", peri.t, peri.v);
const aph = argExtreme(sunDistance, "2025-06-20", "2025-07-20", "max");
row("Earth aphelion", aph.t, aph.v);
console.log(`Sun distance on 2025-01-04: ${sunDistance(new Date("2025-01-04T12:00:00Z")).toFixed(4)} AU`);
console.log(`Sun distance on 2025-07-03: ${sunDistance(new Date("2025-07-03T12:00:00Z")).toFixed(4)} AU`);
for (const [label, when, targetAge] of [
["Full moon", "2025-01-13T22:27:00Z", SYNODIC / 2],
["New moon", "2025-01-29T12:36:00Z", 0],
] as const) {
const t = Date.parse(when);
const m = moonPhase(new Date(t));
const shiftDays = wrap180(((targetAge - m.age) / SYNODIC) * 360) / 360 * SYNODIC;
const modelT = t + shiftDays * 86_400_000;
console.log(
`${label.padEnd(10)} real ${stamp(t)} -> "${m.name}", ${(m.illumination * 100).toFixed(1)}% lit;` +
` model peaks ${stamp(modelT)} (${(shiftDays * 24).toFixed(1)} h)`,
);
}Opposition and conjunction are found by heliocentric longitude (planet and Earth on the same side of the Sun, or opposite sides), not by distance, because they are defined by geometry. The output, in UTC:
Mars closest approach 2025-01-12 16:00 0.6412 AU
Mars opposition 2025-01-16 03:00 0.6426 AU
Mars conjunction 2026-01-09 12:00 2.4038 AU
Jupiter opposition 2024-12-07 20:00 4.0870 AU
Earth perihelion 2025-01-03 12:00 0.9833 AU
Earth aphelion 2025-07-05 03:00 1.0167 AU
Sun distance on 2025-01-04: 0.9833 AU
Sun distance on 2025-07-03: 1.0167 AU
Full moon real 2025-01-13 22:27 -> "Full Moon", 99.8% lit; model peaks 2025-01-14 07:36 (9.2 h)
New moon real 2025-01-29 12:36 -> "New Moon", 0.2% lit; model peaks 2025-01-29 01:58 (-10.6 h)Tip: Two
tsxgotchas, with current tsx and Node versions. In a project without"type": "module", a.tsfile compiles to CommonJS and top-levelawaitfails withTop-level await is currently not supported with the "cjs" output format; name the file.mts. On Windows,import("C:\\...")fails withERR_UNSUPPORTED_ESM_URL_SCHEMEbecausec:looks like a URL scheme, so convert the path withpathToFileURL(...).href.
Computed vs reference
| Event | Reference | Computed by astro.ts |
|---|---|---|
| Mars closest approach | 2025-01-12, about 0.642 AU | 2025-01-12 16:00, 0.6412 AU |
| Mars solar conjunction | 2026-01-09 | 2026-01-09 12:00, 2.4038 AU |
| Jupiter opposition | 2024-12-07, about 4.09 AU (roughly 612 million km) | 2024-12-07 20:00, 4.0870 AU |
| Earth perihelion | 2025-01-04, 0.9833 AU | 0.9833 AU that day; model minimum 2025-01-03 |
| Earth aphelion | 2025-07-03, about 1.0166 AU (about 152.09 million km) | 1.0167 AU that day; model maximum 2025-07-05 |
| Full moon | 2025-01-13 22:27 UTC | 99.8% lit; model full 9.2 h later |
| New moon | 2025-01-29 12:36 UTC | 0.2% lit; model new 10.6 h earlier |
Every event lands on the right day or within a day or two. Earth's perihelion distance matches to four decimals, and aphelion comes out about 0.00005 AU (some 8,000 km) high. Mars's closest approach is a thousandth of an AU short, and Jupiter's 4.087 AU agrees with the roughly 4.09 AU quoted for that opposition.
What the misses tell you
Mars, 0.6412 vs 0.642 AU. That's the dropped inclination, the size the estimate predicted. Putting it back reproduces the published value. Save this next to astro.ts; it adds inclination I and ascending node O from the same JPL table:
import { distanceFromEarth, julianDate } from "./astro";
const DEG = Math.PI / 180;
type Pair = [number, number]; // [value at J2000, change per Julian century]
// Same JPL table, now with inclination I and longitude of ascending node O (degrees)
const ELEMENTS_3D = {
earth: { a: 1.00000261, e: [0.01671123, -0.00004392], I: [-0.00001531, -0.01294668],
L: [100.46457166, 35999.37244981], w: [102.93768193, 0.32327364], O: [0, 0] },
mars: { a: 1.52371034, e: [0.0933941, 0.00007882], I: [1.84969142, -0.00813131],
L: [-4.55343205, 19140.30268499], w: [-23.94362959, 0.44441088], O: [49.55953891, -0.29257343] },
} satisfies Record<string, { a: number; e: Pair; I: Pair; L: Pair; w: Pair; O: Pair }>;
function helio3d(planet: keyof typeof ELEMENTS_3D, d: Date): [number, number, number] {
const el = ELEMENTS_3D[planet];
const T = (julianDate(d) - 2_451_545.0) / 36_525;
const at = ([v, rate]: Pair) => v + rate * T;
const e = at(el.e), L = at(el.L), w = at(el.w), O = at(el.O), I = at(el.I) * DEG;
const M = ((((L - w) % 360) + 540) % 360 - 180) * DEG;
let E = M + e * Math.sin(M);
for (let i = 0; i < 8; i++) E -= (E - e * Math.sin(E) - M) / (1 - e * Math.cos(E));
const xp = el.a * (Math.cos(E) - e);
const yp = el.a * Math.sqrt(1 - e * e) * Math.sin(E);
// Argument of perihelion = longitude of perihelion - node
const co = Math.cos((w - O) * DEG), so = Math.sin((w - O) * DEG);
const cO = Math.cos(O * DEG), sO = Math.sin(O * DEG);
const cI = Math.cos(I), sI = Math.sin(I);
return [
(co * cO - so * sO * cI) * xp + (-so * cO - co * sO * cI) * yp,
(co * sO + so * cO * cI) * xp + (-so * sO + co * cO * cI) * yp,
so * sI * xp + co * sI * yp,
];
}
const d = new Date("2025-01-12T16:00:00Z");
const [ex, ey, ez] = helio3d("earth", d);
const [mx, my, mz] = helio3d("mars", d);
console.log("2D:", distanceFromEarth("mars", d).toFixed(4), "AU");
console.log("3D:", Math.hypot(mx - ex, my - ey, mz - ez).toFixed(4), "AU");2D: 0.6412 AU
3D: 0.6423 AUClosest approach is not opposition. The model puts opposition about three and a half days after closest approach, matching the real ordering in January 2025; Mars's eccentric orbit separates the two. The same happens at the far end: in the model, the greatest Earth-Mars distance came in late November 2025, weeks before conjunction, because Mars was heading towards perihelion and closing on the Sun.
Earth's perihelion and aphelion dates drift. The distances are close, but the model's extremes land a day or more from the published dates. Most of that is the barycentre detail: the elements describe the Earth-Moon centre of mass, and the real Earth swings around it by roughly 4,700 km every month. Earth's distance from the Sun barely changes near perihelion and aphelion, so that small wobble moves the date of the extreme by a day or so. It's also why the real perihelion date shifts from year to year. The 8,000 km aphelion gap isn't the barycentre, though: with the Moon near first quarter, Earth's offset pointed mostly sideways to the Sun line. It's most likely the approximate elements' own error.
The Moon is 9.2 h late at full and 10.6 h early at new, in the same month. A wrong reference constant would push both errors the same way. Opposite signs mean that half-lunation really was longer than average: 15.59 days from full to new, against a mean of 14.77. That's the real Moon's non-uniform motion, which a mean model can't capture.
Note: The site's comment says the reference new moon is 2000-01-06 18:14 UTC, but
2451550.1, a value common in short moon-phase snippets, is 14:24 UTC. The precise JD is2451550.26. Swapping it in moves every prediction about 3.8 hours later: the full moon error above grows to about 13 h while the new moon error shrinks to about 7 h. The epoch isn't the limiting factor; the mean month is.
When to use a real ephemeris
This approach is right when you want a plausible live number with zero network requests: no API keys, no rate limits, works offline. It is wrong when someone will act on the result. Reach for a real ephemeris when you need arcsecond positions, rise and set times, the Moon's position rather than its phase, phase times to the minute, dates outside roughly 1800-2050, or spacecraft. JPL Horizons has a web interface and an HTTP API; for libraries, astronomy-engine covers JavaScript and TypeScript, and Skyfield or Astropy cover Python. For Mars clocks, compare against NASA's Mars24.
Warning: These functions read
new Date(), so don't call them while server-rendering markup that React will hydrate. The server's clock and the browser's differ by however long the page took to arrive or, for a statically generated page, by however long ago it was built: a textbook hydration mismatch. Compute them on the client, after mount or in an event handler, as the terminal does.
The lesson from this file isn't orbital mechanics. A hundred lines of formulas felt finished until a short script compared them with the sky, and that script found the inclination gap, the barycentre drift and a 60 s bug that is easy to miss on a read-through.