Skip to content

Instantly share code, notes, and snippets.

@ashour
Last active January 10, 2020 17:57
Show Gist options
  • Save ashour/d6fbd067dbd68f051cef1b584464f971 to your computer and use it in GitHub Desktop.
Save ashour/d6fbd067dbd68f051cef1b584464f971 to your computer and use it in GitHub Desktop.
// Some configrable constants we need to do our work:
/**
* Past this number of days we'll no longer display the
* day of the week and instead we'll display the date
* with the month
*/
const DATE_WITH_MONTH_THRESHOLD_IN_DAYS: number = 6;
/**
* Past this number of seconds it's now longer "now" when
* we're displaying dates
*/
const NOW_THRESHOLD_IN_SECONDS: number = 10;
/**
* Past this number of hours we'll no longer display "hours
* ago" and instead we'll display "today"
*/
const TODAY_AT_THRESHOLD_IN_HOURS: number = 12;
// The actual work starts here:
/**
* Retrieve a human-friendly date string relative to now and in the
* current locale e.g. "two minutes ago"
*/
function humanFriendlyDate(date: Date): string {
const unixTimestamp: number = millisecondsToSeconds(date.valueOf());
const now: number = millisecondsToSeconds(Date.now());
const diffComponents: DateTimeComponents =
getDateTimeComponents(now - unixTimestamp);
const { years, months, days, hours, minutes, seconds } = diffComponents;
if (years > 0) {
return formatLocalizedDateWithOrdinal(currentLocale,
date,
{ includeYear: true });
}
if (months > 0 || days > DATE_WITH_MONTH_THRESHOLD_IN_DAYS) {
return formatLocalizedDateWithOrdinal(currentLocale,
date,
{ includeYear: false });
}
if (days > 1) {
return date.toLocaleDateString(currentLocale, { weekday: "long" });
}
if (days === 1) {
return __("yesterday");
}
if (hours > TODAY_AT_THRESHOLD_IN_HOURS) {
return __("today at") + " " +
date.toLocaleTimeString(currentLocale,
{ hour: "numeric", minute: "2-digit" });
}
if (hours > 0) {
return _p("hours ago", hours);
}
if (minutes > 0) {
return _p("minutes ago", minutes);
}
if (seconds > NOW_THRESHOLD_IN_SECONDS) {
return _p("seconds ago", seconds);
}
return __("just now");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment