Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 41 additions & 1 deletion app/javascript/helpers/date_helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,49 @@ export function signedDifferenceInDays(fromDate, toDate) {
}

export function beginningOfDay(date) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate())
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
}