You-Dont-Need-Momentjs
You-Dont-Need-Momentjs copied to clipboard
What about timeago.js ?
What about timeago.js as alternative (2kb) ? https://github.com/hustcc/timeago.js
TimeAgo does not allow you to manipulate dates, like add, subtract, check if a given date is inside or not a given gap... all it seems to be doing if leverage the fromNow()
from momentJs and other into it's own library... or am I wrong?
You are right, but it is a perfect alternative if you only need to print out the elapsed time, no?
You are right, but it is a perfect alternative if you only need to print out the elapsed time, no?
... the vanilla JS version for that functionality alone is a ~10-15 line JS snippet.
export function ago(timestamp: Number, max = 5) {
var strTime = ["second", "minute", "hour", "day", "month", "year"];
var length = ["60", "60", "24", "30", "12", "10"];
var diff:any = Math.floor(Date.now() / 1000) - timestamp;
if (diff >= 0) {
for (var i = 0; diff >= length[i] && i < max - 1; i++) {
diff = diff / length[i]
}
diff = Math.round(diff);
return diff + " " + strTime[i] + (diff > 1 ? "s" : "") + " ago";
}
}
Another approach I found useful combining with the native Intl.RelativeTimeFormat:
const durations = [
{ unit: 'seconds', length: 60 },
{ unit: 'minutes', length: 60 },
{ unit: 'hours', length: 24 },
{ unit: 'days', length: 30 },
{ unit: 'months', length: 12 },
{ unit: 'years', length: 100 },
]
let fromNow = Math.round((new Date(date) - new Date()) / 1000)
const foundDuration = durations.find((duration) => {
if (Math.abs(fromNow) >= duration.length) {
fromNow = Math.round(fromNow / duration.length)
return false
}
return true
})
return new Intl.RelativeTimeFormat().format(fromNow, foundDuration.unit)
Works for times in the past and future always showing the smallest time unit that is smaller than the unit limit, e.g.
in 5 days
in 1 hour
5 minutes ago
26 days ago