Skip to content

Instantly share code, notes, and snippets.

@maradondt
Last active December 8, 2022 10:37
Show Gist options
  • Save maradondt/8288f312cac585b68f93ea03a41321f7 to your computer and use it in GitHub Desktop.
Save maradondt/8288f312cac585b68f93ea03a41321f7 to your computer and use it in GitHub Desktop.
luxon time ago string
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