Skip to content

Commit 74b215a

Browse files
committed
fix relative time format cutoff times
1 parent 05be8ea commit 74b215a

File tree

1 file changed

+17
-19
lines changed

1 file changed

+17
-19
lines changed

src/index.php

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<?php
22

3-
define('VERSION', '2.0.1');
3+
define('VERSION', '2.0.2');
44

55
define('PUBLIC_FOLDER', __DIR__ . '/public');
66

@@ -343,32 +343,30 @@ public function __toString(): string
343343
<script data-turbolinks-eval="false" src="https://cdn.jsdelivr.net/npm/darkreader@4.9/darkreader.min.js"></script>
344344
<script>
345345
$[if `process.env.DATE_FORMAT === "relative"`]$
346-
function getRelativeTimeString(
347-
date,
348-
lang = navigator.language
349-
) {
350-
// Allow dates or times to be passed
346+
function getRelativeTimeString(date, lang = navigator.language) {
351347
const timeMs = typeof date === "number" ? date : date.getTime();
352-
353-
// Get the amount of seconds between the given date and now
354348
const deltaSeconds = Math.round((timeMs - Date.now()) / 1000);
355349

356-
// Array reprsenting one minute, hour, day, week, month, etc in seconds
357350
const cutoffs = [60, 3600, 86400, 86400 * 7, 86400 * 30, 86400 * 365, Infinity];
358-
359-
// Array equivalent to the above but in the string representation of the units
360351
const units = ["second", "minute", "hour", "day", "week", "month", "year"];
361352

362-
// Grab the ideal cutoff unit
363-
const unitIndex = cutoffs.findIndex(cutoff => cutoff > Math.abs(deltaSeconds));
353+
// Find the ideal cutoff unit by iterating manually
354+
let unitIndex = 0;
355+
while (unitIndex < cutoffs.length && Math.abs(deltaSeconds) >= cutoffs[unitIndex]) {
356+
unitIndex++;
357+
}
358+
359+
// Calculate the time difference in the current unit
360+
const timeInCurrentUnit = Math.abs(deltaSeconds) / (unitIndex ? cutoffs[unitIndex - 1] : 1);
361+
362+
// Adjust the displayed time based on the 50% threshold
363+
const adjustedTime = Math.floor(timeInCurrentUnit);
364364

365-
// Get the divisor to divide from the seconds. E.g. if our unit is "day" our divisor
366-
// is one day in seconds, so we can divide our seconds by this to get the # of days
367-
const divisor = unitIndex ? cutoffs[unitIndex - 1] : 1;
365+
// Include the negative sign for time that has passed
366+
const sign = deltaSeconds < 0 ? "-" : "";
368367

369-
// Intl.RelativeTimeFormat do its magic
370-
const rtf = new Intl.RelativeTimeFormat(lang, { /* style:"short", */ numeric: "auto" });
371-
return rtf.format(Math.floor(deltaSeconds / divisor), units[unitIndex]);
368+
const rtf = new Intl.RelativeTimeFormat(lang, { numeric: "auto" });
369+
return rtf.format(sign + adjustedTime, units[unitIndex]);
372370
}
373371
$[end]$
374372

0 commit comments

Comments
 (0)