Search code examples
javascriptdate-formattingdate-fns

Formatting time difference as `mm:ss` with date fns


I'm currently using https://date-fns.org/v2.21.1/docs/differenceInSeconds to format distance between 2 dates in seconds, but if such distance is greater than 1min, various results come up like 67 seconds.

To make it more user friendly, I'd like to format this distance as mm:ss so

00:59 01:00 02:34

And so on. Currently closest I got to is using differenceInSeconds and differenceInMinutes and just concatenating 2 into a string like ${differenceInMinutes}:${differenceInSeconds} issue is, that for 2 minutes I get result like 02:120


Solution

  • You need to use the modulo (%) operator, it returns the remainder of division. I've also used the padStart function to have the leading zeros displayed in the final string.

    As the argument you just need to use the difference in seconds,

    Here's a code snippet:

    function formatTime(time) {
      // Remainder of division by 60
      var seconds = time % 60;
      // Divide by 60 and floor the result (get the nearest lower integer)
      var minutes = Math.floor(time / 60); 
    
      // Put it all in one string
      return ("" + minutes).padStart(2, "0") + ":" + ("" + seconds).padStart(2, "0");
    }
    
    console.log(formatTime(15))
    console.log(formatTime(65))
    console.log(formatTime(123))