-
-
Save zaosoula/8667c2750f67b1ca6833345e286dfc3c to your computer and use it in GitHub Desktop.
Twitter style relative time.
This file contains 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
const computeRelativeTime = (time) => { | |
if(typeof time === 'string') { | |
return computeRelativeTime(new Date(time)); | |
} | |
const plural = (val) => val !== 1 ? 's' : ''; | |
const format = (val, unit) => `${val} ${unit}${plural(val)} ago`; | |
let diff = (Date.now() - time.getTime()) / 1000; | |
if (diff<60) { | |
return format(diff, 'second'); | |
} | |
diff = Math.round(diff/60); | |
if (diff<60) { | |
return format(diff, 'minute'); | |
} | |
diff = Math.round(diff/60); | |
if (diff<24){ | |
return format(diff, 'hour'); | |
} | |
diff = Math.round(diff/24); | |
if (diff<7){ | |
return format(diff, 'day'); | |
} | |
diff = Math.round(diff/7); | |
if (diff<4){ | |
return format(diff, 'week'); | |
} | |
return `on ${time.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })}`; | |
} |
This file contains 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
const computeRelativeTime = (time: string | Date): string => { | |
if(typeof time === 'string') { | |
return computeRelativeTime(new Date(time)); | |
} | |
const plural = (val: number) => val !== 1 ? 's' : ''; | |
const format = (val: number, unit: string) => `${val} ${unit}${plural(val)} ago`; | |
let diff = (Date.now() - time.getTime()) / 1000; | |
if (diff<60) { | |
return format(diff, 'second'); | |
} | |
diff = Math.round(diff/60); | |
if (diff<60) { | |
return format(diff, 'minute'); | |
} | |
diff = Math.round(diff/60); | |
if (diff<24){ | |
return format(diff, 'hour'); | |
} | |
diff = Math.round(diff/24); | |
if (diff<7){ | |
return format(diff, 'day'); | |
} | |
diff = Math.round(diff/7); | |
if (diff<4){ | |
return format(diff, 'week'); | |
} | |
return `on ${time.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })}`; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment