我当前正在使用https://date-fns.org/v2.21.1/docs/differenceInSeconds以秒为单位格式化两个日期之间的距离,但如果该距离大于1分钟,则会出现各种结果,如67
秒。
为了更方便用户,我想将此距离格式化为mm:ss
,因此
00:59
01:00
02:34
等等。目前我最接近的是使用differenceInSeconds
和differenceInMinutes
,只需将2连接成一个类似${differenceInMinutes}:${differenceInSeconds}
的字符串,问题是,在2分钟内,我得到了类似02:120
的结果
您需要使用modulo(%
(运算符,它返回除法的余数。我还使用了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))