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”.
I’ve written in detail about the problems of parsing time and explained how this module works in this blog post.
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