readable-seconds

https://www.npmjs.com/package/readable-seconds ← Back

What is it?

An npm module which converts time in seconds into something human readable, complete with punctuation, conjunctions and nouns where appropriate.

Technologies

  • »JavaScript
  • »npm
  • »NodeJS
Screenshot of readable-seconds npm package

Background

Parsing time is a notoriously difficult thing to do and in most cases it’s better to rely on a pre-existing module to do the work for you than to try and do it yourself. There are many good time-parsing modules out there, notably moment.js which is a fantastic package and one that I’ve made extensive use of myself, but is more suited to working with dates and did not quite provide the functionality I wanted. What I wanted was a module that could take any number of seconds and then convert it to a string like “1 hour, 1 minute and 30 seconds”.

How does it work?

I’ve written in detail about the problems of parsing time and explained how this module works in this blog post.

Under the hood

This module converts seconds into years, days, hours, minutes and seconds. A human-readable string is returned. Units with values of 0 are omitted and all the values returned are followed by the relevant unit type which will be appropriately singular or plural depending on the value. The units are separated by commas if there are more than 2 and the last value is preceded by the word “and”.

An optional second argument can be provided to limit the number of units returned to the 2 largest units. This can be useful when dealing with large numbers of units where the smaller units are of less significance, as in the following example:

console.log(readableSeconds(31622490)); // 1 year, 1 day, 1 minute and 30 seconds
console.log(readableSeconds(31622490, 2)); // 1 year and 1 day

Links

npm module
Source code

Recent Projects

A screenshot of Treasure Dash gameplay

Treasure Dash

Treasure Dash was a game idea which I'd previously made with a friend as a group project in university. The initial version was written in Java but it was very basic and unfinished. I decided to rebuild the project for the web and bring our initial vision to life. Continue reading »


Prisoner’s Dilemma Strategy Simulator

The Prisoner's Dilemma is a hugely influential game in the field of Game Theory. In Richard Dawkins' seminal 1976 book, The Selfish Gene, he describes a competition organised by political scientist Robert Axelrod in which competitors could submit code for strategies for playing the game which were then pitted against each other. In this NodeJS app, I implement my own version… Continue reading »