diff --git a/src/night.ts b/src/night.ts index 526e67f..30a5567 100644 --- a/src/night.ts +++ b/src/night.ts @@ -88,3 +88,46 @@ export const getSolarTransit = ( } /*****************************************************************************************************************/ + +/** + * + * getNight() + * + * Calculates the start and end of the next night for the observer at the given date. + * + * @param date - The date to calculate the extent of the next night for. + * @param observer - The geographic coordinates of the observer. + * @param horizon - The horizon altitude to use for the calculation. + * @param temperature - The temperature to use for the calculation. + * @param pressure - The pressure to use for the calculation. + * @returns The start and end of the next night for the observer. + * + */ +export const getNight = ( + datetime: Date, + observer: GeographicCoordinate, + horizon: number = -12, + temperature: number = 288.15, + pressure: number = 101325 +): { + start: Date | null + end: Date | null +} => { + const { sunset } = getSolarTransit(datetime, observer, horizon, temperature, pressure) + + const { sunrise } = getSolarTransit( + new Date(datetime.getTime() + 60000 * 60 * 24), + observer, + horizon, + temperature, + pressure + ) + + // The observer could be in perpetual daylight or perpetual night, e.g., the North Pole or South Pole: + return { + start: sunset, + end: sunrise + } +} + +/*****************************************************************************************************************/ diff --git a/tests/night.spec.ts b/tests/night.spec.ts index e963f92..fbaccf7 100644 --- a/tests/night.spec.ts +++ b/tests/night.spec.ts @@ -10,7 +10,7 @@ import { describe, expect, it } from 'vitest' /*****************************************************************************************************************/ -import { getSolarTransit } from '../src' +import { getSolarTransit, getNight } from '../src' /*****************************************************************************************************************/ @@ -67,3 +67,28 @@ describe('getSolarTransit', () => { }) /*****************************************************************************************************************/ + +describe('getNight', () => { + it('should be defined', () => { + expect(getNight).toBeDefined() + }) + + it('should return the correct night for the observer at a horizon of 0 degrees', () => { + const { start, end } = getNight( + datetime, + { + latitude, + longitude + }, + 0 + ) + + expect(start).toBeInstanceOf(Date) + expect(end).toBeInstanceOf(Date) + + expect(start?.toISOString()).toBe('2021-05-14T19:56:00.000Z') + expect(end?.toISOString()).toBe('2021-05-15T04:45:00.000Z') + }) +}) + +/*****************************************************************************************************************/