Create local time formatter to match the previous format we were generating server-side

This commit is contained in:
Jorge Manrubia
2025-04-25 08:55:36 +02:00
parent 6fb0d88079
commit 4657663e35
4 changed files with 27 additions and 5 deletions
@@ -2,7 +2,9 @@ import { Controller } from "@hotwired/stimulus"
import { differenceInDays } from "helpers/date_helpers"
export default class extends Controller {
static targets = [ "time", "date", "datetime", "shortdate", "ago", "indays", "daysago" ]
static targets = [ "time", "date", "datetime", "shortdate", "ago", "indays", "daysago", "agoorweekday" ]
static values = { refreshInterval: Number }
static classes = [ "local-time-value"]
#timer
@@ -13,7 +15,10 @@ export default class extends Controller {
this.dateTimeFormatter = new Intl.DateTimeFormat(undefined, { timeStyle: "short", dateStyle: "short" })
this.agoFormatter = new AgoFormatter()
this.daysagoFormatter = new DaysAgoFormatter()
this.datewithweekdayFormatter = new Intl.DateTimeFormat(undefined, { weekday: "long", month: "long", day: "numeric" })
this.datewithweekdayFormatter = new Intl.DateTimeFormat(undefined, { weekday: "long", month: "long", day: "numeric" })
this.indaysFormatter = new InDaysFormatter()
this.agoorweekdayFormatter = new DaysAgoOrWeekdayFormatter()
}
connect() {
@@ -60,6 +65,10 @@ export default class extends Controller {
this.#formatTime(this.daysagoFormatter, target)
}
agoorweekdayTargetConnected(target) {
this.#formatTime(this.agoorweekdayFormatter, target)
}
#refreshRelativeTimes() {
this.agoTargets.forEach(target => {
this.#formatTime(this.agoFormatter, target)
@@ -111,6 +120,18 @@ class DaysAgoFormatter {
}
}
class DaysAgoOrWeekdayFormatter {
format(date) {
const days = differenceInDays(date, new Date())
if (days <= 1) {
return new DaysAgoFormatter().format(date)
} else {
return new Intl.DateTimeFormat(undefined, { weekday: "long", month: "long", day: "numeric" }).format(date)
}
}
}
class InDaysFormatter {
format(date) {
const days = differenceInDays(new Date(), date)