Skip to content

Instantly share code, notes, and snippets.

@mort3za
Created April 2, 2022 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mort3za/c4a60284ab73537fe29baefb1a44165d to your computer and use it in GitHub Desktop.
Save mort3za/c4a60284ab73537fe29baefb1a44165d to your computer and use it in GitHub Desktop.
Relative time with automatic period detection
// example: const mydate = getRelativeTime('Sat Apr 02 2022 14:00:00 GMT');
// console.log(getRelativeTime(mydate);
// output: 4 hr. ago
// (while current time is 18:00)
export const getRelativeTime = (date: string): string => {
const unix = new Date(date).getTime();
type Periods = [string, number][];
const second = 1000;
const minute = 60 * second;
const hour = 60 * minute;
const day = 24 * hour;
const week = 7 * day;
const month = 30 * day;
const year = 365 * day;
const periods = [
["minute", minute],
["hour", hour],
["day", day],
["week", week],
["month", month],
["year", year],
] as Periods;
const now = new Date().getTime();
let diff = now - unix;
let output_period: [Intl.RelativeTimeFormatUnit, number] = ["second", 1];
for (const [unit, period] of periods) {
if (diff < period) {
break;
}
output_period = [unit, period] as [Intl.RelativeTimeFormatUnit, number];
}
diff = Math.round(diff / output_period[1]);
const rtf = new Intl.RelativeTimeFormat("en", { style: "narrow", numeric: "auto" });
return rtf.format(-diff, output_period[0]);
};
@mort3za
Copy link
Author

mort3za commented Apr 2, 2022

Format a date:

export const formatDateTime = (date: string): string => {
  const dateStr = new Date(date);
  return new Intl.DateTimeFormat("en-GB", { dateStyle: "medium", timeStyle: "medium" }).format(dateStr);
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment