Search code examples
date-fns

Format a duration ( from seconds ) using date-fns


Given int value 1807, format to 30:07 using date-fns?

Yes, I know this can be achieved with vanilla js, but is this possible using date-fns?


Solution

  • You can do this using date-fns by simple modifying an intermediate helper date. Using new Date( 0 ) you'll get a date set to January 1, 1970, 00:00:00 UTC. You can then use addSeconds from date-fns to add the relevant seconds (actually you could use the native date setTime( 1000 * seconds ) for this). Formatting the minutes and seconds of this will give you your desired result.

    var input = document.getElementById('seconds');
    var output = document.getElementById('out');
    
    output.innerText = formattedTime(input.value);
    input.addEventListener('input', function() {
      output.innerText = formattedTime(input.value);
    });
    
    function formattedTime(seconds) {
      var helperDate = dateFns.addSeconds(new Date(0), seconds);
      return dateFns.format(helperDate, 'mm:ss');
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.26.0/date_fns.min.js"></script>
    
    <input type="number" id="seconds" value="1807">
    <pre id="out"></pre>