Git Product home page Git Product logo

lunarphase-js's Introduction

Lunar phase

Calculate phase of the moon using Julian date.

Getting Started

To install, execute:

npm i lunarphase-js

Then, import into a project and use as:

import { Moon } from "lunarphase-js";

const phase = Moon.lunarPhase();

This package provides for following distributables:

  • CJS: CommonJS
  • ESM: ES Modules
  • UMD: Universal Module Definition (browser)
  • IIFE: Immediately invoked function expression
  • TypeScript declaration types

Usage

In the lunar calendar there are 8 phases each synodic month, which is the number of days to complete the cycle. This time between two identical syzygies is equivalent to 29.53059 Earth days.

Lunar phases, in order:

Phase Northern Hemisphere Southern Hemisphere
New ๐ŸŒ‘ ๐ŸŒ‘
Waxing Crescent ๐ŸŒ’ ๐ŸŒ˜
First Quarter ๐ŸŒ“ ๐ŸŒ—
Waxing Gibbous ๐ŸŒ” ๐ŸŒ–
Full ๐ŸŒ• ๐ŸŒ•
Waning Gibbous ๐ŸŒ– ๐ŸŒ”
Last Quarter ๐ŸŒ— ๐ŸŒ“
Waning Crescent ๐ŸŒ˜ ๐ŸŒ’

API Reference:

The following functions are exported from Moon:

Function Output Description
lunarPhase() Waxing Gibbous Get lunar phase for a given date
lunarPhaseEmoji() ๐ŸŒ– Get emoji of lunar phase for a given date
isWaxing() true Whether the moon is waxing
isWaning() false Whether the moon is waning
lunarAge() 11.367344279004676 Earth days since the last new moon
lunarAgePercent() 0.38497186542446116 Percentage through the lunar synodic month
lunarDistance() 56.04166690080031 Distance to the moon measured in units of Earth radii
lunationNumber() 1217 Brown Lunation Number (BLN)

Visit this repository's GitHub Pages for a live example: https://jasonsturges.github.io/lunarphase-js/

All functions default to the current date, as in "now":

import { Moon } from "lunarphase-js";

const phase = Moon.lunarPhase();

Otherwise, pass a date object to each function for a specific date.

import { Moon } from "lunarphase-js";

const date = new Date();
const phase = Moon.lunarPhase(date);

Lunar Phase

To get the current lunar phase from the LunarPhase enum (ex: "FULL")

const phase = Moon.lunarPhase();

Lunar Phase Emoji

To get the current lunar phase emoji from the LunarEmoji (ex: "๐ŸŒ•"):

const phaseEmoji = Moon.lunarPhaseEmoji();

As phases are inverted between Northern and Southern Hemispheres, optionally pass Hemisphere options.

import { Hemisphere, Moon } from "lunarphase-js";

const date = new Date();
Moon.lunarPhaseEmoji(date, {
  hemisphere: Hemisphere.SOUTHERN,
});

To get emoji for other lunar phases, pass a LunarPhase enum:

import { LunarPhase, Moon } from "lunarphase-js";

const emoji = Moon.emojiForLunarPhase(LunarPhase.FULL);

Optionally pass a Hemisphere to the function:

import { Hemisphere, LunarPhase, Moon } from "lunarphase-js";

const emoji = Moon.emojiForLunarPhase(LunarPhase.FULL, {
  hemisphere: Hemisphere.SOUTHERN,
});

Waxing

Whether the moon is waxing (ex: false)

const waxing = Moon.isWaxing();

Waning

Whether the moon is waning (ex: true)

const waning = Moon.isWaning();

Lunar Age

Age in Earth days through the current lunar cycle, equivalent to 29.53059 Earth days, based on Mean Synodic Month, 2000 AD mean solar days.

Phase Start Event End
New 0 1.84566173161
Waxing Crescent 1.84566173161 3.69132346322 5.53698519483
First Quarter 5.53698519483 7.38264692644 9.22830865805
Waxing Gibbous 9.22830865805 11.07397038966 12.91963212127
Full 12.91963212127 14.76529385288 16.61095558449
Waning Gibbous 16.61095558449 18.4566173161 20.30227904771
Last Quarter 20.30227904771 22.14794077932 23.99360251093
Waning Crescent 23.99360251093 25.83926424254 27.68492597415
New 27.68492597415 29.53058770576

To get the lunar age (ex: 16.54412413414952)

const age = Moon.lunarAge();

Lunar Age Percent

To get the percentage through the lunar cycle (ex: 0.5602368519132597)

const agePercent = Moon.lunarAgePercent();

Lunation Number

Brown Lunation Number (BLN), per Ernest William Brown's lunar theory, defining Lunation 1 as the first new moon of 1923 at approximately 02:41 UTC, January 17, 1923

const lunationNumber = Moon.lunationNumber();

Lunar Distance

Distance to the moon measured in units of Earth radii, with perigee at 56 and apogee at 63.8.

const distance = Moon.lunarDistance();

Julian

Convert to and from Gregorian Dates to Julian Days via the Julian module.

API Reference:

Function Output Description
fromDate() 2459357.5380029744 Convert date to Julian Day
toDate() 2021-05-23T05:56:10.418Z Convert Julian Day to date

To convert a date to Julian day:

import { Julian } from "lunarphase-js";

const date = new Date();
const julian = Julian.fromDate(date);

To convert a Julian day to a date:

import { Julian } from "lunarphase-js";

const julian = 2459356.529302257;
const date = Julian.toDate(julian);

lunarphase-js's People

Contributors

jasonsturges avatar probablyrory avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

lunarphase-js's Issues

consider adding multiple language, and next new moon/full moon? Here is my code

export function calculateMoonPhase(currentDate: Date): number {
  const newMoonDate = new Date(Date.UTC(2019, 0, 6, 1, 28, 0)); // Reference New Moon date
  const lunarCycleLength = 29.53; // Average length of the lunar cycle in days
  const diffInDays = (currentDate.getTime() - newMoonDate.getTime()) / (1000 * 3600 * 24);
  const moonPhase = (diffInDays % lunarCycleLength) / lunarCycleLength;
  return moonPhase;
}


export function estimateNextMoonPhases(currentDate: Date): { nextNewMoon: string, nextFullMoon: string} {
  const currentMoonPhase = calculateMoonPhase(currentDate);
  const lunarCycleLength = 29.53; // Average length of the lunar cycle in days

  let daysUntilNextNewMoon = lunarCycleLength * (1 - currentMoonPhase);
  if (currentMoonPhase >= 0 && currentMoonPhase < 0.5) {
      daysUntilNextNewMoon = lunarCycleLength * (0.5 - currentMoonPhase);
  }

  let daysUntilNextFullMoon = lunarCycleLength * (0.5 - currentMoonPhase);

  if (currentMoonPhase >= 0.5) {
      daysUntilNextFullMoon = lunarCycleLength * (1 - currentMoonPhase) + (lunarCycleLength / 2);
  }

  const nextNewMoon = formatMMDDDate(new Date(currentDate.getTime() + daysUntilNextNewMoon * 24 * 3600 * 1000));
  const nextFullMoon = formatMMDDDate(new Date(currentDate.getTime() + daysUntilNextFullMoon * 24 * 3600 * 1000));
  return { nextNewMoon, nextFullMoon };
}


export function getMoonPhaseName(moonPhase: number): string {
  if(moonPhase < 0.03 || moonPhase > 0.97) {
      return "NewMoon";
  } else if(moonPhase < 0.22) {
      return "WaxingCrescent";
  } else if(moonPhase < 0.28) {
      return "FirstQuarter";
  } else if(moonPhase < 0.47) {
      return "WaxingGibbous";
  } else if(moonPhase < 0.53) {
      return "FullMoon";
  } else if(moonPhase < 0.72) {
      return "WaningGibbous";
  } else if(moonPhase < 0.78) {
      return "LastQuarter";
  } else {
      return "WaningCrescent";
  }
}


export function getMoonPhasesForPeriod(currentDate: Date = new Date()): MoonPhase[] {
    const todayMoonPhaseNumber = calculateMoonPhase(currentDate);
    const todayMoonPhaseName = getMoonPhaseName(todayMoonPhaseNumber);
    const { nextNewMoon, nextFullMoon } = estimateNextMoonPhases(currentDate);
  
    const today: MoonPhase = {
      date: formatMMDDDate(currentDate),
      moonPhaseIcon: MoonPhaseIcons[todayMoonPhaseName],
      name: todayMoonPhaseName,
    };
  
    const nextNewMoonPhase: MoonPhase = {
      date: nextNewMoon,
      moonPhaseIcon: MoonPhaseIcons["NewMoon"],
      name: "NewMoon",
    };
  
    const nextFullMoonPhase: MoonPhase = {
      date: nextFullMoon,
      moonPhaseIcon: MoonPhaseIcons["FullMoon"],
      name: "FullMoon",
    };
  
    // Determine the sequence based on current phase
    let phases: MoonPhase[];
    if (todayMoonPhaseNumber < 0.5) {
      // Today -> Next Full Moon -> Next New Moon
      phases = [today, nextFullMoonPhase, nextNewMoonPhase];
    } else {
      // Today -> Next New Moon -> Next Full Moon
      phases = [today, nextNewMoonPhase, nextFullMoonPhase];
    }
  
    return phases;
}

New moon time is wrong

Since the lib doesn't have a method to directly calculate new moon time, I approximated it checking lunarAgePercent:

2023-02-20T00:20:00.000Z -> 0.9999708226112602
2023-02-20T00:21:00.000Z -> 0.9999943387321082
2023-02-20T00:22:00.000Z -> 0.00001785483715366354
2023-02-20T00:23:00.000Z -> 0.00004137094219913706

So it says, that February new moon is Feb 20, 0:22UTC, but public data and pyephem library say that it will be 7:06UTC

Add Lunation Number

Per discussion #1, adding Brown Lunation Number (BLN).

Lunation Number

Brown Lunation Number (BLN), per Wikipedia:

...defines lunation 1 as beginning at the first new moon of 1923, the year when Ernest William Brown's lunar theory was introduced in the American Ephemeris and Nautical Almanac.[citation needed] Lunation 1 occurred at approximately 02:41 UTC, January 17, 1923.

Primary and intermediate phases

This has come up repeatedly, and need to isolate some notion of primary an intermediary phases.

Primary phases occur at a specific moment in time, and include:

  • New Moon
  • First Quarter
  • Full Moon
  • Last Quarter

Intermediate phases are ~7.4 days and do not occur at a specific moment in time. They include:

  • Waxing Crescent
  • Waxing Gibbous
  • Waning Gibbous
  • Waning Crescent

API not yet determined to implement this.

get future key dates

Is there a way to get the future dates for key events (full moon, half moon etc)? Right now, it seems like the caller would have to get the current position of the moon and then do calculations. If this is a common request, it might be nice to put this functional in the library.

what I'm looking for is a way to get all the full, half moon for a range of dates: ie the current month, next few months

it would be nice if the api could take a range of dates (start and end) and return the key dates

this issue might be similar to #24

๐Ÿ’ก Additional use case.

@jasonsturges very cool little package and article ๐Ÿ‘

I wonder how one might use Julian date and lunar age to arrive at the date/time when the last new moon was and when the next new moon will be.

how to know which HEMISPHERE?

Considering how important this parameter is, is there any way to know which Hemisphere the user is from?
Perhaps it's out of scope for this library;
if we forward the iso country code, or the country (from react-native-localize for example), would it be possible to have a mapping function in this library to get the user's hemisphere?

Edit: I have found the following online:

window.whatHemisphere= (function(){
    var y= new Date().getFullYear();
    if(y.getTimezoneOffset()==undefined) return null;
    var jan= -(new Date(y, 0, 1, 0, 0, 0, 0).getTimezoneOffset()),
    jul= -(new Date(y, 6, 1, 0, 0, 0, 0).getTimezoneOffset()),
    diff= jan-jul;
    if(diff> 0) return 'N';
    if(diff< 0) return 'S'
    return null;
})()

do you think it could do the trick, and perhaps be part of your library?

Full moon, new moon, first quarter, and last quarter too long

This plugin is telling me the moon phases in the title last 3 to 4 days. However, these phases only happen on one moment. While waning/waxing gibbous/crescent can last multiple days, the other phases cannot.

'2021-10-20': 'full',
  '2021-10-21': 'full',
  '2021-10-22': 'full',
  '2021-10-23': 'waning-gibbous',
  '2021-10-24': 'waning-gibbous',
  '2021-10-25': 'waning-gibbous',
  '2021-10-26': 'waning-gibbous',
  '2021-10-27': 'last-quarter',
  '2021-10-28': 'last-quarter',
  '2021-10-29': 'last-quarter',
  '2021-10-30': 'last-quarter',
  '2021-10-31': 'waning-crescent',
  '2021-11-01': 'waning-crescent',
  '2021-11-02': 'waning-crescent',
  '2021-11-03': 'waning-crescent',
  '2021-11-04': 'new',
  '2021-11-05': 'new',
  '2021-11-06': 'new',
  '2021-11-07': 'waxing-crescent',
  '2021-11-08': 'waxing-crescent',
  '2021-11-09': 'waxing-crescent',
  '2021-11-10': 'waxing-crescent',
  '2021-11-11': 'first-quarter',
  '2021-11-12': 'first-quarter',
  '2021-11-13': 'first-quarter',
  '2021-11-14': 'first-quarter',
  '2021-11-15': 'waxing-gibbous',
  '2021-11-16': 'waxing-gibbous',
  '2021-11-17': 'waxing-gibbous',

Moon.lunarPhase() anticipating moon phase

Hi Jason! Thanks for creating this library.
I have been using it for a couple of weeks and just noticed that the method Moon.lunarPhase(date); is returning "New Moon" phase on Jan 31, 2022 at 5pm EST. However, New Moon is going to be in effect on Feb 01, 2022 at 12:46 am EST.

Moon position calculations

  • Latitude and Longitude
  • Angle
  • Altitude of moon at sunset in degrees
  • Direction of moon at sunset
  • Direction - raising / falling

CDN

Any option to use the library via CDN or as a minified JS file? (in other words: non-NPM setups)

bug: NexJS build: `problem ReferenceError: exports is not defined in ES module scope`

Description

Hello @jasonsturges, I just updated the package to 2.0.2 and I am receiving this error below,

Collecting page data  ...ReferenceError: exports is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/Users/douglasmendes/Git/xpertsea/web-insights/node_modules/lunarphase-js/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///Users/douglasmendes/Git/xpertsea/web-insights/node_modules/lunarphase-js/dist/index.cjs.js:1:36
    at ModuleJob.run (node:internal/modules/esm/module_job:218:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:329:24)
    at async importModuleDynamicallyWrapper (node:internal/vm/module:430:15)

I think this change might be impacting the build for nextJS for production:

https://github.com/jasonsturges/lunarphase-js/commit/38fca43a8a09105bd3d8790a7f895510c421ac7b#diff-7ae45ad102eab3b6d7e7[โ€ฆ]470d7bc6507b6481575d519R19

Renaming the file from index.cjs.js to index.cjs resolved the build issue successfully locally.

Lunar Day Calculation

Cool library. How about adding a lunarDay method to calculate the lunar day. Seems doable by dividing the lunar age. On the new moon it'd return 1 and so on. Returning a float would work or have lunarDay return a floored integer and accompany it with a lunarDayPercent method that returns how far into that day we are. Thoughts?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.