-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
73 lines (60 loc) · 2.29 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* Returns the day of the year.
* @param date - Date object.
* @param startAtZero - Whether the day of the year should be zero-based.
* @returns Day of year,
*/
export function getDayOfYear(date: Date, startAtZero = false): number {
const year = date.getFullYear()
const januaryFirst = new Date(year, 0, 1)
const givenDate = new Date(year, date.getMonth(), date.getDate())
return (
Math.round((givenDate.getTime() - januaryFirst.getTime()) / 86_400_000) +
(startAtZero ? 0 : 1)
)
}
/**
* Returns a date string in the modern Julian format. (i.e. YYYYDDD)
* ex. 2023-01-01 => '2023001'
* @param date - Date object.
* @returns Date string in modern Julian format
*/
export function toModernJulianDate(date: Date): string {
const dayOfYear = getDayOfYear(date)
return (date.getFullYear() * 1000 + dayOfYear).toString()
}
/**
* Returns a date string in the modern Julian format with a two-digit year. (i.e. YYDDD)
* ex. 2023-01-01 => '23001'
* @param date - Date object.
* @returns Date string in modern Julian format with a two-digit year
*/
export function toShortModernJulianDate(date: Date): string {
return toModernJulianDate(date).slice(2)
}
/**
* Converts a modern Julian date into a Javascript Date object.
* ex. '2023001' => 2023-01-01
* @param modernJulianDate - A five-digit (short) or seven-digit modern Julian date. Note that five-digit dates will be assumed to be in the current century.
* @returns Date object.
*/
export function fromModernJulianDate(modernJulianDate: string): Date {
let sevenDigitModernJulianDate = modernJulianDate
if (modernJulianDate.length === 5) {
sevenDigitModernJulianDate =
Math.floor(new Date().getFullYear() / 100).toString() + modernJulianDate
}
if (sevenDigitModernJulianDate.length !== 7) {
throw new Error(`Invalid modern Julian date: ${modernJulianDate}`)
}
const year = Number.parseInt(sevenDigitModernJulianDate.slice(0, 4))
const days = Number.parseInt(sevenDigitModernJulianDate.slice(4))
if (Number.isNaN(year) || Number.isNaN(days) || days > 366) {
throw new TypeError(`Invalid modern Julian date: ${modernJulianDate}`)
}
// eslint-disable-next-line sonarjs/no-identical-expressions
const date = new Date(year, 1 - 1, 1)
date.setDate(days)
return date
}
export default toModernJulianDate