Created
January 7, 2020 19:54
-
-
Save dylanpyle/be38b20f758544a1bef0703c0ff7608e to your computer and use it in GitHub Desktop.
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 SECOND = 1000; // ms | |
const MINUTE = 60 * SECOND; | |
const HOUR = 60 * MINUTE; | |
const DAY = 24 * HOUR; | |
const WEEK = 7 * DAY; | |
const MONTH = 4 * WEEK; | |
export function formatRelativeTimestamp(date: Date): string { | |
const agoMs = Date.now() - date.getTime(); | |
if (agoMs < 30 * SECOND) { | |
return 'just now'; | |
} else if (agoMs < HOUR) { | |
const minutes = Math.ceil(agoMs / MINUTE); | |
if (minutes > 1) { | |
return `${minutes} minutes ago`; | |
} else { | |
return 'less than a minute ago'; | |
} | |
} else if (agoMs < DAY) { | |
const hours = Math.ceil(agoMs / HOUR); | |
const plural = (hours > 1) ? 'hours' : 'hour'; | |
return `${hours} ${plural} ago`; | |
} else if (agoMs < WEEK) { | |
const days = Math.ceil(agoMs / DAY); | |
const plural = (days > 1) ? 'days' : 'day'; | |
return `${days} ${plural} ago`; | |
} else if (agoMs < MONTH) { | |
const weeks = Math.ceil(agoMs / WEEK); | |
const plural = (weeks > 1) ? 'weeks' : 'week'; | |
return `${weeks} ${plural} ago`; | |
} else { | |
const months = Math.ceil(agoMs / MONTH); | |
const plural = (months > 1) ? 'months' : 'month'; | |
return `${months} ${plural} ago`; | |
} | |
} | |
const obj: { [key: number]: any } = {}; | |
const start = Date.now(); | |
for (let i = 0; i < 10000; i++) { | |
obj[i] = formatRelativeTimestamp(new Date()); | |
} | |
console.log('did in ', Date.now() - start, 'ms'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment