Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

What about timeago.js ? #90

Open
jorwan opened this issue Mar 6, 2020 · 4 comments
Open

What about timeago.js ? #90

jorwan opened this issue Mar 6, 2020 · 4 comments

Comments

@jorwan
Copy link

jorwan commented Mar 6, 2020

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

@balexandre
Copy link

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?

@jorwan
Copy link
Author

jorwan commented May 9, 2020

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

@bloor
Copy link

bloor commented Jul 5, 2023

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

@rambii
Copy link

rambii commented Jul 27, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants