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

Screenshot of Podsend homepage

Podsend

A React single-page application (SPA) which processes the data from podcast RSS feeds and provides key facts such as how long the podcast has existed, what the longest ever episode is and the average time between releases. Continue reading »

Screenshot of Argmana web app

Argmana

A simple anagram game. Choose a topic from the highest grossing films of all time to Ballon d'Or winners and test your knowledge by seeing if you can decipher the anagrams. Continue reading »