Created
April 30, 2020 21:16
-
-
Save amitlzkpa/692bf3ee754d488e69c7278f5aeb3fe2 to your computer and use it in GitHub Desktop.
show pretty dates
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
// ref: https://stackoverflow.com/questions/7641791/javascript-library-for-human-friendly-relative-date-formatting | |
function fuzzyTime(date) { | |
var delta = Math.round((+new Date - date) / 1000); | |
var minute = 60, | |
hour = minute * 60, | |
day = hour * 24, | |
week = day * 7; | |
var fuzzy; | |
if (isNaN(delta)) { | |
fuzzy = '---'; | |
} else if (delta < 30) { | |
fuzzy = 'just now'; | |
} else if (delta < minute) { | |
fuzzy = `${delta} seconds ago`; | |
} else if (delta < 2 * minute) { | |
fuzzy = 'a minute ago' | |
} else if (delta < hour) { | |
fuzzy = `${Math.floor(delta / minute)} minutes ago`; | |
} else if (Math.floor(delta / hour) == 1) { | |
fuzzy = '1 hour ago' | |
} else if (delta < day) { | |
fuzzy = `${Math.floor(delta / hour)} hours ago`; | |
} else if (delta < day * 2) { | |
fuzzy = 'yesterday'; | |
} else if (delta < day * 10) { | |
fuzzy = `${Math.floor(delta / day)} days ago`; | |
} else { | |
fuzzy = `${date.toDateString()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`; | |
} | |
return fuzzy; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment