使用日期 fns 将时差格式化为 `mm:ss`

问题描述

我目前正在使用 https://date-fns.org/v2.21.1/docs/differenceInSeconds 以秒为单位格式化 2 个日期之间的距离,但如果该距离大于 1 分钟,则会出现各种结果,例如 67 秒。

为了让用户更友好,我想将此距离格式化为 mm:ss 所以

00:59 01:00 02:34

等等。目前我最接近的是使用 differenceInSecondsdifferenceInMinutes 并且只是将 2 连接成一个字符串,例如 ${differenceInMinutes}:${differenceInSeconds} 问题是,在 2 分钟内我得到的结果是 02:120

解决方法

您需要使用模 (%) 运算符,它返回除法的余数。 我还使用 padStart 函数在最终字符串中显示前导零。

作为参数,您只需要使用以秒为单位的差异,

这是一个代码片段:

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))