From 6f3fc6daab0c0a39c2594145113050e18bb319e1 Mon Sep 17 00:00:00 2001 From: jableader Date: Tue, 15 Oct 2024 19:46:17 +1100 Subject: [PATCH] date format plurals --- src/dateformats.js | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/dateformats.js b/src/dateformats.js index fcdabc0..5425fde 100644 --- a/src/dateformats.js +++ b/src/dateformats.js @@ -1,3 +1,8 @@ +function plural(num, unit) { + num = Math.floor(num); + return num + " " + unit + (num === 1 ? "" : "s"); +} + export function ago(date) { const now = new Date(); const diff = now - date; @@ -5,16 +10,16 @@ export function ago(date) { return "just now"; } if (diff < 60 * 1000) { - return Math.floor(diff / 1000) + " seconds ago"; + return plural(diff / 1000, "second") + " ago"; } if (diff < 60 * 60 * 1000) { - return Math.floor(diff / (60 * 1000)) + " minutes ago"; + return plural(diff / (60 * 1000), "minute") + " ago"; } if (diff < 24 * 60 * 60 * 1000) { - return Math.floor(diff / (60 * 60 * 1000)) + " hours ago"; + return plural(diff / (60 * 60 * 1000), "hour") + " ago"; } if (diff < 7 * 24 * 60 * 60 * 1000) { - return Math.floor(diff / (24 * 60 * 60 * 1000)) + " days ago"; + return plural(diff / (24 * 60 * 60 * 1000), "day") + " ago"; } return date.toLocaleDateString(); } \ No newline at end of file