Skip to content

Seconds ago in JavaScript

A couple of weeks ago I needed a way to convert a number of seconds to a more user friendly format for a project I’m working on. I’ve seen these called “ago” functions. They take a raw number of seconds and convert it to something friendly like “3 seconds ago” or “5 minutes ago.” Not quite what I wanted though. I was looking for something that counted seconds up to a minute and then minutes and seconds after that. For what I need, it wouldn’t ever go past minutes.

Rather than explain though, here’s an example.


And like always, StackOverflow came through. It took a little reformatting to get exactly what I was after, and ended up like this.

And here’s the code where it’s implemented for this page. I guess you could look at the page source if you really wanted to, but here it is to make it easier.

You might need to build on this a bit depending on how much time you’ll have to account for. In my case about 2 minutes is the highest the clock should ever get so this code is enough.

Published inCoding

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *