Last active
December 8, 2022 10:37
-
-
Save maradondt/8288f312cac585b68f93ea03a41321f7 to your computer and use it in GitHub Desktop.
luxon time ago string
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
import { DateTime } from 'luxon'; | |
const units: Intl.RelativeTimeFormatUnit[] = ['year', 'month', 'week', 'day', 'hour', 'minute', 'second']; | |
/** | |
* https://github.com/moment/luxon/issues/274#issuecomment-649347238 | |
* | |
* @param dateTime DateTime.fromISO(isoString) | |
* @returns string | |
* | |
* @example | |
* ```ts | |
* timeAgo(DateTime.fromISO(publish_date_time)) // -> 19 hours ago | |
* ``` | |
*/ | |
export const timeAgo = (dateTime: DateTime) => { | |
const diff = dateTime.diffNow().shiftTo(...units); | |
const unit = units.find((unit) => diff.get(unit) !== 0) || 'second'; | |
const relativeFormatter = new Intl.RelativeTimeFormat('en', { | |
numeric: 'auto', | |
}); | |
return relativeFormatter.format(Math.trunc(diff.as(unit)), unit); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment