Format time interval in seconds as X hour(s) Y minute(s) Z second(s)

Viewed 3836

Is it possible to format seconds in a countdown style? For example, if I have var seconds = 3662, how can I show: 1 hour 1 minute 2 seconds.

I tried using formatDistanceStrict(3662) but this is only printing the hour: 1 hour.

Is there a built-in method to show the minutes and seconds too? I don't want to write 100 lines of code to get this working (like other examples from internet)

4 Answers

The simplest solution I could find, using the date-fns library, is this:

import { formatDuration, intervalToDuration } from 'date-fns';

function humanDuration(time: number) {
    return formatDuration(intervalToDuration({start: 0, end: time * 1000}));
};
humanDuration(463441); // 5 days 8 hours 44 minutes 1 second

Is that, what you mean?

const seconds = 3662,

      formatCounter = s => {
        let _s = s        
        const units = {day: 864e2, hour: 3600, minute: 60, second: 1},
              str = Object
                .entries(units)
                .reduce((r, [unit, multiplier]) => {            
                  if(_s >= multiplier){
                    const count = _s/multiplier|0,
                          tail = count > 1 ? 's' : ''
                    r.push([count, unit+tail])              
                    _s = _s%multiplier
                  }
                  return r
                }, [])
        return str.flat().join(' ')               
      } 
      
console.log(formatCounter(seconds))
console.log(formatCounter(416920))

Are you looking for this.

Here I have converted seconds to minutes and hours

and returned the string.

function format(time) {   
    // Hours, minutes and seconds
    var hrs = ~~(time / 3600);
    var mins = ~~((time % 3600) / 60);
    var secs = ~~time % 60;

    // Output like "1:01" or "4:03:59" or "123:03:59"
    var ret = "";
    if (hrs > 0) {
        ret += "" + hrs + " hour " + (mins < 10 ? "0" : "");
    }
    ret += "" + mins + " minutes " + (secs < 10 ? "0" : "");
    ret += "" + secs + " seconds";
    return ret;
}

console.log(format(3662));

As simple as:

    const time = new Date(0,0,0)
    time.setSeconds(3662)
    console.log(time.getHours(), 
               time.getMinutes(), 
               time.getSeconds())

Related