Handle times on the client to make this cache-friendly

This commit is contained in:
Jorge Manrubia
2025-04-04 14:35:24 +02:00
parent 977199e189
commit 488e96b20b
3 changed files with 32 additions and 30 deletions
@@ -11,6 +11,7 @@ export default class extends Controller {
this.shortDateFormatter = new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric" })
this.dateTimeFormatter = new Intl.DateTimeFormat(undefined, { timeStyle: "short", dateStyle: "short" })
this.agoFormatter = new AgoFormatter()
this.daysAgoFormatter = new DaysAgoFormatter()
this.indaysFormatter = new InDaysFormatter()
}
@@ -42,6 +43,10 @@ export default class extends Controller {
this.#formatTime(this.agoFormatter, target)
}
daysAgoTargetConnected(target) {
this.#formatTime(this.daysAgoFormatter, target)
}
indaysTargetConnected(target) {
this.#formatTime(this.indaysFormatter, target)
}
@@ -87,6 +92,22 @@ class AgoFormatter {
}
}
class DaysAgoFormatter {
format(dt) {
const now = new Date()
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate())
const startOfGivenDay = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate())
const msPerDay = 1000 * 60 * 60 * 24
const dayDiff = Math.floor((startOfToday - startOfGivenDay) / msPerDay)
if (dayDiff === 0) return "Today"
if (dayDiff === 1) return "Yesterday"
return `in ${dayDiff} days`
}
}
class InDaysFormatter {
format(dt) {
const target = this.#beginningOfDay(dt)