Skip to content

Instantly share code, notes, and snippets.

@Xe

Xe/moon-phase.ts Secret

Created November 22, 2023 13:52
Show Gist options
  • Save Xe/c3fdc15d7d1a244b97e2b1e751739da2 to your computer and use it in GitHub Desktop.
Save Xe/c3fdc15d7d1a244b97e2b1e751739da2 to your computer and use it in GitHub Desktop.
const getJulianDate = (date = new Date()) => {
const time = date.getTime();
const tzoffset = date.getTimezoneOffset();
return (time / 86400000) - (tzoffset / 1440) + 2440587.5;
};
const LUNAR_MONTH = 29.530588853;
const getLunarAge = (date = new Date()) => {
const percent = getLunarAgePercent(date);
const age = percent * LUNAR_MONTH;
return age;
};
const getLunarAgePercent = (date = new Date()) => {
return normalize((getJulianDate(date) - 2451550.1) / LUNAR_MONTH);
};
const normalize = (value: number) => {
value = value - Math.floor(value);
if (value < 0) {
value = value + 1;
}
return value;
};
export const getLunarPhase = (date = new Date()) => {
const age = getLunarAge(date);
if (age < 1.84566) {
return "New";
} else if (age < 5.53699) {
return "Waxing Crescent";
} else if (age < 9.22831) {
return "First Quarter";
} else if (age < 12.91963) {
return "Waxing Gibbous";
} else if (age < 16.61096) {
return "Full";
} else if (age < 20.30228) {
return "Waning Gibbous";
} else if (age < 23.99361) {
return "Last Quarter";
} else if (age < 27.68493) {
return "Waning Crescent";
}
return "New";
};
export const isWaxing = (date = new Date()) => {
const age = getLunarAge(date);
return age <= 14.765;
};
export const isWaning = (date = new Date()) => {
const age = getLunarAge(date);
return age > 14.765;
};
import { getLunarPhase } from "@/lib/moon-phase.ts";
function moonPhaseToEmoji(phase: string) {
switch (phase) {
case "Waxing Crescent":
return "πŸŒ’";
case "First Quarter":
return "πŸŒ“";
case "Waxing Gibbous":
return "πŸŒ”";
case "Full Moon":
return "πŸŒ•";
case "Waning Gibbous":
return "πŸŒ–";
case "Last Quarter":
return "πŸŒ—";
case "Waning Crescent":
return "🌘";
default:
return "πŸŒ‘";
}
}
export default function MoonPhase() {
const phase = getLunarPhase();
const emoji = moonPhaseToEmoji(phase);
return (
<span
title={`Current lunar phase: ${phase}`}
className="text-xl mt-2"
style="font-family:Papyrus"
>
{emoji}
</span>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment