惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

宝玉的分享
宝玉的分享
酷 壳 – CoolShell
酷 壳 – CoolShell
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
S
Security @ Cisco Blogs
小众软件
小众软件
D
Docker
博客园_首页
A
About on SuperTechFans
P
Privacy International News Feed
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
A
Arctic Wolf
Spread Privacy
Spread Privacy
有赞技术团队
有赞技术团队
T
Tailwind CSS Blog
Latest news
Latest news
WordPress大学
WordPress大学
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
T
The Exploit Database - CXSecurity.com
C
Cybersecurity and Infrastructure Security Agency CISA
大猫的无限游戏
大猫的无限游戏
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
K
Kaspersky official blog
V2EX - 技术
V2EX - 技术
SecWiki News
SecWiki News
U
Unit 42
GbyAI
GbyAI
H
Hackread – Cybersecurity News, Data Breaches, AI and More
L
LINUX DO - 热门话题
S
Security Affairs
Y
Y Combinator Blog
aimingoo的专栏
aimingoo的专栏
Blog — PlanetScale
Blog — PlanetScale
MongoDB | Blog
MongoDB | Blog
博客园 - 【当耐特】
The GitHub Blog
The GitHub Blog
T
Tenable Blog
W
WeLiveSecurity
Cloudbric
Cloudbric
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
G
Google Developers Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
N
Netflix TechBlog - Medium
F
Full Disclosure
N
News and Events Feed by Topic
D
DataBreaches.Net
P
Proofpoint News Feed
B
Blog RSS Feed
B
Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Computing Moon Phase in 150 Lines of JavaScript — Julian Date, Synodic Month, and SVG Terminator
SEN LLC · 2026-05-20 · via DEV Community

"Wait, what phase is the moon in tonight?" — that question deserves a 150-line answer, not a Google search. The math is small: convert the date to Julian Date, divide the days since a reference new moon by the synodic month (29.530588853 days), take the fractional part. The interesting bit is drawing it: the moon's terminator (the line between lit and dark) is an elliptical arc when projected to a plane, which means the whole moon glyph can be expressed as two SVG arc commands. Here's how.

moon-phase UI: large waxing crescent SVG rendered top-left. To the right, info table with phase name

🌐 Demo: https://sen.ltd/portfolio/moon-phase/
📦 GitHub: https://github.com/sen-ltd/moon-phase

Architecture: pure module + DOM glue

The whole pure-math layer is one file:

import { moonPhase, terminatorPath, nextFullMoon } from "./phase.js";

const info = moonPhase(new Date());
// → { phase: 0.1141, age: 3.4, illumination: 0.123, name: "三日月", waxing: true }

const svgPath = terminatorPath(info.phase, 100);
// → "M 0 -100 A 100 100 0 0 1 0 100 A 80.9 100 0 0 0 0 -100 Z"

Enter fullscreen mode Exit fullscreen mode

No DOM access in phase.js, which means node --test can run every test without jsdom. The UI script just imports the pure functions and writes the path string into an SVG element.

Julian Date: the astronomer's serial day number

Astronomical math hates the Gregorian calendar (variable month lengths, leap years, leap seconds…). Astronomers count time by Julian Date (JD) instead: a continuous count of days starting at noon UT on January 1, 4713 BC. One day = 1.0, time-of-day is the fractional part.

Convert Unix milliseconds to JD with one constant:

export const UNIX_EPOCH_JD = 2440587.5;       // JD of 1970-01-01 00:00 UTC
export const MS_PER_DAY = 86400000;

export function dateToJulian(date) {
  if (!(date instanceof Date) || Number.isNaN(date.getTime())) return null;
  return date.getTime() / MS_PER_DAY + UNIX_EPOCH_JD;
}

Enter fullscreen mode Exit fullscreen mode

Why the .5? Julian Days start at noon, not midnight (so that astronomers' single observing nights don't cross a day boundary). Midnight UT is half a day past JD noon → +0.5.

Pin it:

test("dateToJulian matches the unix epoch as JD 2440587.5", () => {
  assert.equal(dateToJulian(new Date("1970-01-01T00:00:00Z")), 2440587.5);
});

Enter fullscreen mode Exit fullscreen mode

Phase = (JD − reference new moon) / synodic month mod 1

The synodic month — new moon to new moon — averages 29.530588853 days.

For a reference new moon, the convention is JD 2451550.1 (2000-01-06 14:24 UTC). NASA's ephemeris confirms a new moon at that instant.

export const SYNODIC_MONTH = 29.530588853;
export const REFERENCE_NEW_MOON_JD = 2451550.1;

export function moonPhase(date) {
  const jd = dateToJulian(date);
  const daysSinceRef = jd - REFERENCE_NEW_MOON_JD;
  let phase = (daysSinceRef / SYNODIC_MONTH) % 1;
  if (phase < 0) phase += 1;
  // ...
}

Enter fullscreen mode Exit fullscreen mode

phase ∈ [0, 1) where 0 = new, 0.25 = first quarter, 0.5 = full, 0.75 = last quarter.

The negative-modulo gotcha

JavaScript's % is truncated modulo, not mathematical modulo. If the dividend is negative, the result is negative:

-3 % 10   // → -3 in JS  (Python would say 7)

Enter fullscreen mode Exit fullscreen mode

For dates before the reference new moon (early 2000), daysSinceRef is negative and so is the phase. The if (phase < 0) phase += 1 normalises it. Test the round-trip both forward and backward:

test("moonPhase at the reference new moon JD gives phase ≈ 0", () => {
  const d = julianToDate(REFERENCE_NEW_MOON_JD);
  const info = moonPhase(d);
  assert.ok(info.phase < 0.001 || info.phase > 0.999);
});

test("moonPhase one synodic month after the reference is again ~new", () => {
  const d = julianToDate(REFERENCE_NEW_MOON_JD + SYNODIC_MONTH);
  const info = moonPhase(d);
  assert.ok(info.phase < 0.001 || info.phase > 0.999);
});

Enter fullscreen mode Exit fullscreen mode

Illumination = (1 − cos(2π × phase)) / 2

The lit fraction of the moon as seen from Earth is a linear transform of the cosine of the phase angle:

const illumination = (1 - Math.cos(2 * Math.PI * phase)) / 2;

Enter fullscreen mode Exit fullscreen mode

phase cos(2π × phase) illumination
0 (new) 1 0
0.25 (first quarter) 0 0.5
0.5 (full) -1 1
0.75 (last quarter) 0 0.5

First quarter and last quarter are indistinguishable from illumination alone. The waxing flag (phase < 0.5) is the other axis.

The terminator is an elliptical arc — two SVG arcs draw the entire lit area

This is the bit I found cute. The terminator — the boundary between the lit and dark sides of the moon — is a great circle on the lunar surface. Projected onto the plane of view, it becomes an ellipse. So the lit portion of the moon disc can be decomposed as:

  1. A half-circle outer arc (the lit edge of the moon)
  2. A half-ellipse inner arc (the terminator)

With semi-minor axis r × |cos(2π × phase)|:

export function terminatorPath(phase, radius) {
  if (phase < 0.001 || phase > 0.999) return "";              // new moon: nothing lit
  if (Math.abs(phase - 0.5) < 0.001) return circlePath(radius); // full moon: whole disc

  const cosPhase = Math.cos(2 * Math.PI * phase);
  const minor = Math.abs(cosPhase) * radius;
  const r = radius;
  const waxing = phase < 0.5;

  const outerSweep = waxing ? 1 : 0;
  const innerSweep = cosPhase < 0 ? 1 : 0;

  return [
    `M 0 ${-r}`,
    `A ${r} ${r} 0 0 ${outerSweep} 0 ${r}`,
    `A ${minor} ${r} 0 0 ${innerSweep} 0 ${-r}`,
    "Z",
  ].join(" ");
}

Enter fullscreen mode Exit fullscreen mode

SVG arc sweep flag, demystified

A rx ry x-axis-rotation large-arc-flag sweep-flag x y. The sweep flag is the gotcha:

  • 0 — arc traced counter-clockwise from start to end
  • 1 — arc traced clockwise from start to end

For a half-circle from (0, -r) (top) to (0, r) (bottom):

  • waxing (lit on the right) → clockwise → sweep flag 1
  • waning (lit on the left) → counter-clockwise → sweep flag 0

Why cosPhase's sign tells you the inner sweep

The inner half-ellipse needs to either bulge into the lit side (crescent — terminator carves the lit area down to a sliver) or bulge into the dark side (gibbous — terminator pushes the lit area beyond half the disc).

cos(2π × phase) flips sign at exactly the right moments:

  • phase ∈ (0, 0.25) — waxing crescent — cos > 0 — ellipse on the lit side
  • phase ∈ (0.25, 0.5) — waxing gibbous — cos < 0 — ellipse bulges into dark
  • phase ∈ (0.5, 0.75) — waning gibbous — cos < 0 — ellipse bulges into dark
  • phase ∈ (0.75, 1) — waning crescent — cos > 0 — ellipse on the lit side

So innerSweep = cosPhase < 0 ? 1 : 0 covers all four cases in one line. Pin it:

test("terminatorPath gibbous bulges into dark side (sweep flag 1 on inner arc)", () => {
  const path = terminatorPath(0.4, 100);   // waxing gibbous
  const arcs = path.match(/A [^A]+/g);
  assert.equal(arcs.length, 2);
  assert.ok(arcs[1].includes("0 0 1 0"));   // inner arc sweep flag = 1
});

Enter fullscreen mode Exit fullscreen mode

Next new/full moon: closed-form, no binary search

"When's the next full moon?" — the naive solution loops day-by-day looking for |phase - 0.5| < ε. But phase is a linear function of JD, so just invert it:

phase(jd) = ((jd - REF) / S) mod 1

jd at the next phase = target:
  REF + (target + k) × S   for the smallest integer k where this > startJd

Enter fullscreen mode Exit fullscreen mode

export function nextPhase(date, target) {
  const startJd = dateToJulian(date);
  const offset = (startJd - REFERENCE_NEW_MOON_JD) / SYNODIC_MONTH;
  const k = Math.ceil(offset - target);
  const jd = REFERENCE_NEW_MOON_JD + (target + k) * SYNODIC_MONTH;
  return julianToDate(jd);
}

Enter fullscreen mode Exit fullscreen mode

offset is "how many synodic months past the reference, including fractional position". Math.ceil(offset - target) picks the smallest integer k such that target + k > offset, i.e., the next time the phase wraps around to target.

Verify by checking that consecutive new moons are exactly one synodic month apart:

test("consecutive new moons are ~SYNODIC_MONTH days apart", () => {
  const first = nextNewMoon(new Date("2024-01-01T00:00:00Z"));
  const second = nextNewMoon(new Date(first.getTime() + 86400000));  // skip past first
  const diff = (second - first) / 86400000;
  assert.ok(Math.abs(diff - SYNODIC_MONTH) < 0.01);
});

Enter fullscreen mode Exit fullscreen mode

Phase-name binning with a 1/16 offset

Mapping phase ∈ [0, 1) to one of 8 phase names (new, waxing crescent, first quarter, …) needs each canonical phase to land in the centre of its bin, not at a bin edge. Offset by 1/16:

const idx = Math.floor((p + 1 / 16) * 8) % 8;

Enter fullscreen mode Exit fullscreen mode

phase = 0 (new) → (0 + 1/16) × 8 = 0.5 → floor → 0. phase = 0.25 (first quarter) → (0.25 + 1/16) × 8 = 2.5 → 2. Etc. Bin boundaries fall at 1/16, 3/16, 5/16, ..., equidistant from the canonical phases.

test("phaseName maps canonical phases to expected labels", () => {
  assert.equal(phaseName(0),    "新月");          // new
  assert.equal(phaseName(0.25), "上弦の月");     // first quarter
  assert.equal(phaseName(0.5),  "満月");          // full
  assert.equal(phaseName(0.75), "下弦の月");     // last quarter
});

test("phaseName handles wrap-around", () => {
  assert.equal(phaseName(1.0),   "新月");
  assert.equal(phaseName(-0.25), "下弦の月");
});

Enter fullscreen mode Exit fullscreen mode

On accuracy — this is mean-phase, not true-phase

SYNODIC_MONTH = 29.530588853 is a mean value. The actual lunar month varies by about ±7 hours due to Earth's elliptical orbit (faster at perihelion) and the moon's orbital perturbations.

What that means for the code:

  • Casual use ("what phase is the moon in tonight?") — accurate enough
  • Exact new/full moon times — off by up to ±12 hours
  • Astronomical-grade work — use ELP-2000/82 or similar (hundreds of periodic terms)

This trade-off is called out in the README. For 150 lines, ±12 hours is the right amount of accuracy.

TL;DR

  • Julian Date decouples astronomy from calendar arithmetic. JD = unix_ms / 86400000 + 2440587.5.
  • Phase = ((JD - REF_NEW_MOON_JD) / SYNODIC_MONTH) mod 1. Watch JS's negative-modulo behaviour.
  • Illumination = (1 - cos(2π × phase)) / 2. Symmetric around full — track waxing/waning separately.
  • The terminator projects to an ellipse. The whole lit disc is two SVG arcs: a half-circle + a half-ellipse, with sweep flags determined by (waxing, cosPhase sign).
  • Next full/new moon has a closed-form. No bisection needed since phase is linear in JD.
  • Mean synodic month → ±12-hour accuracy for transition times. For sub-minute precision, switch to ELP-2000.

Source: https://github.com/sen-ltd/moon-phase — MIT, ~150 lines of JS + 30 unit tests, zero runtime dependencies, no build step.


🛠 Built by SEN LLC as part of an ongoing series of small, focused developer tools. Browse the full portfolio for more.