-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathdate_helpers.js
More file actions
55 lines (44 loc) · 1.73 KB
/
Copy pathdate_helpers.js
File metadata and controls
55 lines (44 loc) · 1.73 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
export function differenceInDays(fromDate, toDate) {
return Math.round(Math.abs((beginningOfDay(toDate) - beginningOfDay(fromDate)) / (1000 * 60 * 60 * 24)))
}
export function signedDifferenceInDays(fromDate, toDate) {
return Math.round((beginningOfDay(toDate) - beginningOfDay(fromDate)) / (1000 * 60 * 60 * 24))
}
export function beginningOfDay(date) {
const { year, month, day } = datePartsInTimezone(date)
return new Date(Date.UTC(year, month - 1, day))
}
export function secondsToDate(seconds) {
return new Date(seconds * 1000)
}
// Snap a timestamp to midnight using the user's timezone (from the `timezone`
// cookie the server reads too), so client day boundaries match the server's
// and don't follow the browser's resolved timezone, which can differ in a PWA.
function datePartsInTimezone(date) {
return dateFormatter().formatToParts(date).reduce((parts, { type, value }) => {
if (type !== "literal") parts[type] = parseInt(value, 10)
return parts
}, {})
}
let dateFormatterCache
let dateFormatterTimezone
function dateFormatter() {
const timezone = currentTimezone()
if (!dateFormatterCache || dateFormatterTimezone !== timezone) {
dateFormatterTimezone = timezone
dateFormatterCache = buildDateFormatter(timezone)
}
return dateFormatterCache
}
function buildDateFormatter(timezone) {
const options = { year: "numeric", month: "2-digit", day: "2-digit" }
try {
return new Intl.DateTimeFormat("en-US", { ...options, timeZone: timezone })
} catch {
return new Intl.DateTimeFormat("en-US", options)
}
}
function currentTimezone() {
const cookie = document.cookie.split("; ").find(entry => entry.startsWith("timezone="))
return cookie ? decodeURIComponent(cookie.split("=")[1]) : undefined
}