You-Dont-Need-Momentjs icon indicating copy to clipboard operation
You-Dont-Need-Momentjs copied to clipboard

What about timeago.js ?

Open jorwan opened this issue 4 years ago • 4 comments

What about timeago.js as alternative (2kb) ? https://github.com/hustcc/timeago.js

jorwan avatar Mar 06 '20 05:03 jorwan

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?

balexandre avatar Apr 13 '20 14:04 balexandre

You are right, but it is a perfect alternative if you only need to print out the elapsed time, no?

jorwan avatar May 09 '20 22:05 jorwan

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";
    }
}

bloor avatar Jul 05 '23 06:07 bloor

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

rambii avatar Jul 27 '23 09:07 rambii