Repository navigation
Expand file tree
/
Copy pathparse.ts
More file actions
235 lines (228 loc) · 7.77 KB
/
Copy pathparse.ts
File metadata and controls
235 lines (228 loc) · 7.77 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import { date } from "./date"
import { validate, styles, fixedLength, four, two, validOffset, fixedLengthByOffset, offsetToSecs, TimezoneToken } from "./common"
import { formatStr } from "./formatStr"
import { fourDigitYear } from "./fourDigitYear"
import { ap } from "./ap"
import { range } from "./range"
import { monthDays } from "./monthDays"
import { parts } from "./parts"
import type {
ParseOptions,
Format,
Part,
FormatStyle,
FilledPart,
FormatToken,
} from "./types"
export function parse(options: ParseOptions): Date | never
export function parse(
dateStr: string,
format?: Format,
locale?: string
): Date | never
/**
* Parses a date string into a Date object using the given format.
* @param dateStr - A string representing a date.
* @param format - The format the given string is in.
* @param locale - The locale to parse the string from.
*/
export function parse(
dateStrOrOptions: string | ParseOptions,
format: Format = "ISO8601",
locale = "device"
): Date | never {
let partFilter: (part: Part) => boolean = () => true
let dateStr: string
let dateOverflow = "backward"
if (typeof dateStrOrOptions === "object") {
;({
date: dateStr,
format = "ISO8601",
locale = "device",
dateOverflow = "backward",
partFilter = () => true,
} = dateStrOrOptions)
} else {
dateStr = dateStrOrOptions
}
if (!dateStr) throw new Error("parse() requires a date string.")
const invalid = (): never => {
throw new Error(
`Date (${dateStr}) does not match format (${formatStr(format, locale)})`
)
}
if (format === "ISO8601") return date(dateStr)
const genitive =
styles.includes(format as FormatStyle) || typeof format === "object"
const formatParts = validate(parts(format, locale).filter(partFilter))
if (!formatParts.length) throw new Error("parse() requires a pattern.")
let parsedParts
try {
parsedParts = parseParts(dateStr, formatParts)
} catch {
return invalid()
}
const now = new Date()
const parsed = new Map([
["YYYY", now.getFullYear()],
["MM", now.getMonth() + 1],
["DD", now.getDate()],
["HH", 0],
["mm", 0],
["ss", 0],
["SSS", 0],
])
let a: null | boolean = null
let offset = ""
parsedParts.forEach((part): void | never => {
if (part.partName === "literal") return
if (part.token === part.value) return invalid()
const v = Number(part.value)
// Handle SSS specially - convert variable-length fractional seconds to milliseconds
if (part.token === "SSS") {
// "1" -> 100, "12" -> 120, "123" -> 123, "123456" -> 123
const digits = part.value.padEnd(3, "0").slice(0, 3)
parsed.set("SSS", Number(digits))
} else if (parsed.has(part.token)) {
// Parse for YYYY, MM, DD, HH, hh, mm, ss
parsed.set(part.token, v)
} else if (part.token === "YY") {
// Parse for YY
parsed.set("YYYY", fourDigitYear(part.value))
} else {
/* MMM - Short name Jan-Dec
* MMMM - Full name January - December
* h - Minimum hour digits, 12 hour clock, 1-12
* hh - 2 hour digits, 12 hour clock, 01-12
* m - The minute 0-59
* mm - The minute 00-12
* s - The second 0-59
* a - am/pm
* A - AM/PM
*/
const t = part.token
if (t.startsWith("d")) {
// d, ddd, dddd — we just ignore these because they are non specific
return
} else if (t === "D") {
parsed.set("DD", v)
} else if (t === "H" || t.startsWith("h")) {
parsed.set("HH", v)
} else if (t === "M") {
parsed.set("MM", v)
} else if (t === "a" || t === "A") {
a = part.value.toLowerCase() === ap("am", locale).toLowerCase()
} else if (t === "Z" || t === "ZZ") {
offset = validOffset(part.value, t)
} else {
const values = range(t as FormatToken, locale, genitive)
const index = values.indexOf(part.value)
if (index !== -1) {
switch (t) {
case "MMM":
case "MMMM":
parsed.set("MM", index + 1)
break
}
}
}
}
})
let hours = parsed.get("HH") || 0
if (a === false) {
hours += hours === 12 ? 0 : 12
parsed.set("HH", hours === 24 ? 0 : hours)
} else if (a === true && hours === 12) {
// 12am === 00 in 24 hour clock.
parsed.set("HH", 0)
}
parsed.set("MM", (parsed.get("MM") || 1) - 1)
// eslint-disable-next-line prefer-const
let [Y, M, D, h, m, s, ms] = Array.from(parsed.values())
// Determine if the date is valid for the month.
const maxDaysInMonth = monthDays(new Date(`${four(Y)}-${two(M + 1)}-10`))
if (maxDaysInMonth < D && dateOverflow === "throw")
throw new Error(`Invalid date ${four(Y)}-${two(M + 1)}-${two(D)}`)
D = dateOverflow === "backward" ? Math.min(D, maxDaysInMonth) : D
// Create the date.
// If there's an offset, we need to handle it manually because JavaScript's Date
// doesn't support seconds in timezone offsets (e.g., -05:32:11).
const msStr = String(ms).padStart(3, "0")
if (offset) {
// Create the date in UTC, then apply the offset manually
const isoStringUtc = `${four(Y)}-${two(M + 1)}-${two(D)}T${two(h)}:${two(m)}:${two(s)}.${msStr}Z`
const d = new Date(isoStringUtc)
if (!isFinite(+d)) return invalid()
const len = fixedLengthByOffset(offset)
const token: TimezoneToken = len === 5 || len === 8 ? "ZZ" : "Z"
const offsetSecs = offsetToSecs(offset, token)
return new Date(d.getTime() - offsetSecs * 1000)
}
// No offset - create date in local time (original behavior)
const isoString = `${four(Y)}-${two(M + 1)}-${two(D)}T${two(h)}:${two(m)}:${two(s)}.${msStr}`
const d = new Date(isoString)
if (isFinite(+d)) return d
return invalid()
}
/**
* Given a string date and corresponding format parts, fill the parts with the
* data from the string.
* @param dateStr - A string to parse.
* @param formatParts - The expected parts of the given string.
*/
export function parseParts(dateStr: string, formatParts: Part[]): FilledPart[] {
let i = 0
const advance = (parts: Part[]): [Part, Part | undefined] => [
parts[i++],
parts[i],
]
let pos = 0
const parsed: FilledPart[] = []
let n: undefined | Part = undefined
do {
const [current, next] = advance(formatParts)
n = next
let len = 1
if (current.partName === "literal") {
// Literals can be discarded
len = current.partValue.length
} else if (current.partName === "timeZoneName") {
len = fixedLengthByOffset(dateStr.substring(pos))
} else if (current.token === "SSS") {
// Variable length: consume all consecutive digits (gracious parsing)
let end = pos
while (end < dateStr.length && /\d/.test(dateStr.charAt(end))) {
end++
}
len = end - pos
} else if (current.token in fixedLength) {
// Fixed length parse
len = fixedLength[current.token as keyof typeof fixedLength]
} else if (next) {
// Variable length parse.
if (next.partName === "literal") {
len = dateStr.indexOf(next.partValue, pos) - pos
if (len < 0) throw new Error()
} else if (next.partName === "dayPeriod") {
// Our validator is ensuring that the current item must be a variable
// length number. We need to extract it.
for (let i = 1; i <= 4; i++) {
if (isNaN(Number(dateStr.charAt(pos + i)))) {
len = i
break
}
}
} else {
// Our validator guarantees the next is either not a number or it
// will be the end of the string
const nextChar = dateStr.substring(pos).search(/\d/)
if (nextChar !== -1) len = pos + nextChar
}
} else {
len = dateStr.length
}
parsed.push({ ...current, value: dateStr.substring(pos, pos + len) })
pos += len
} while (n)
return parsed
}