Created
April 2, 2022 18:02
-
-
Save mort3za/c4a60284ab73537fe29baefb1a44165d to your computer and use it in GitHub Desktop.
Relative time with automatic period detection
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
// 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]); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Format a date: