Search code examples
javascriptdatetime-formatdate-fns

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


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)


Solution

  • 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