Created
February 20, 2021 13:15
-
-
Save abhagsain/edc72e9a3bcde42fb41c774b07228be6 to your computer and use it in GitHub Desktop.
Get fuzzy time from JS Date.
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
// 1hr ago, 2 days ago etc | |
const getFuzzyTime = (millisec) => { | |
let res = ""; | |
const t_second = 1000; | |
const t_minute = t_second * 60; | |
const t_hour = t_minute * 60; | |
const t_day = t_hour * 24; | |
const t_week = t_day * 7; | |
const t_month = Math.floor(t_day * 30.4); | |
const t_year = t_month * 12; | |
const now = Date.now(); | |
const dif = now - millisec; | |
const fuzzy_string = (time_ref, time_str) => { | |
const fuzzy = Math.floor(dif / time_ref); | |
res += `${fuzzy} ${time_str}`; | |
if (fuzzy !== 1) res += "s"; | |
res += " ago"; | |
}; | |
if (dif >= t_year) fuzzy_string(t_year, "year"); | |
else if (dif >= t_month) fuzzy_string(t_month, "month"); | |
else if (dif >= t_week) fuzzy_string(t_week, "week"); | |
else if (dif >= t_day) fuzzy_string(t_day, "day"); | |
else if (dif >= t_hour) fuzzy_string(t_hour, "hour"); | |
else if (dif >= t_minute) fuzzy_string(t_minute, "minute"); | |
else if (dif >= t_second) fuzzy_string(t_second, "second"); | |
else res = "now"; | |
return res; | |
}; | |
export default getFuzzyTime; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment