Last active
April 18, 2025 01:44
-
-
Save flipeador/d23573b2e38cca27c9684ac8382cd9bf to your computer and use it in GitHub Desktop.
Language-sensitive relative time formatting in JavaScript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Language-sensitive relative time formatting. | |
| * @see https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat | |
| * @example | |
| * // now | |
| * console.log(formatRelativeTime( | |
| * '2000/01/01 00:00:00', | |
| * '2000/01/01 00:00:00' | |
| * )); | |
| * | |
| * // next month | |
| * console.log(formatRelativeTime( | |
| * '2000/02/01 00:00:00', | |
| * '2000/01/01 00:00:00' | |
| * )); | |
| * | |
| * // 2 years ago | |
| * console.log(formatRelativeTime( | |
| * '2000/01/01 00:00:00', | |
| * '2001/01/01 00:00:00' | |
| * )); | |
| */ | |
| function formatRelativeTime(ts1, ts2, fmt) | |
| { | |
| ts1 = (new Date(ts1)).getTime(); | |
| ts2 = ts2 ? (new Date(ts2)).getTime() : Date.now(); | |
| const elapsed = Math.round((ts1 - ts2) / 1000); | |
| const difference = Math.abs(elapsed); | |
| fmt = { numeric: 'auto', ...fmt }; | |
| fmt.units ??= { | |
| year: 31536000, | |
| month: 2629800, | |
| week: 604800, | |
| day: 86400, | |
| hour: 3600, | |
| minute: 60 | |
| }; | |
| const rtf = new Intl.RelativeTimeFormat(fmt?.locale || undefined, fmt); | |
| for (const unit in fmt.units) { | |
| if (difference >= fmt.units[unit]) { | |
| return rtf.format( | |
| Math.floor(elapsed / fmt.units[unit]), | |
| unit | |
| ); | |
| } | |
| } | |
| return rtf.format(elapsed, 'second'); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.