Add daysago formatter and extract common helper to reuse with indays formatter

This commit is contained in:
Jorge Manrubia
2025-04-05 13:24:46 +02:00
parent e30ddca439
commit 8e01a277ad
4 changed files with 33 additions and 32 deletions
@@ -1,7 +1,8 @@
import { Controller } from "@hotwired/stimulus"
import { differenceInDays } from "helpers/date_helpers";
export default class extends Controller {
static targets = [ "time", "date", "datetime", "shortdate", "ago", "indays" ]
static targets = [ "time", "date", "datetime", "shortdate", "ago", "indays", "daysago" ]
#timer
@@ -11,8 +12,8 @@ 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()
this.daysagoFormatter = new DaysAgoFormatter()
}
connect() {
@@ -43,14 +44,14 @@ export default class extends Controller {
this.#formatTime(this.agoFormatter, target)
}
daysAgoTargetConnected(target) {
this.#formatTime(this.daysAgoFormatter, target)
}
indaysTargetConnected(target) {
this.#formatTime(this.indaysFormatter, target)
}
daysagoTargetConnected(target) {
this.#formatTime(this.daysagoFormatter, target)
}
#refreshRelativeTimes() {
this.agoTargets.forEach(target => {
this.#formatTime(this.agoFormatter, target)
@@ -92,27 +93,9 @@ 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 `${dayDiff} days ago`
}
}
class InDaysFormatter {
format(dt) {
const target = this.#beginningOfDay(dt)
const today = this.#beginningOfDay(new Date())
const days = Math.round((target - today) / (1000 * 60 * 60 * 24))
format(date) {
const days = differenceInDays(new Date(), date)
if (days <= 0) {
return "today"
@@ -123,8 +106,19 @@ class InDaysFormatter {
return `in ${Math.round(days)} days`
}
}
#beginningOfDay(dt) {
return new Date(dt.getFullYear(), dt.getMonth(), dt.getDate())
class DaysAgoFormatter {
format(date) {
const days = differenceInDays(date, new Date())
if (days <= 0) {
return "today"
}
if (days === 1) {
return "yesterday"
}
return `${Math.round(days)} days ago`
}
}