在 JavaScript 中将秒转换为分秒

在 JavaScript 中将秒转换为分和秒

Convert Seconds to Minutes and Seconds in JavaScript

将秒转换为分钟和秒:

  1. 通过将秒数除以得到完整的分钟数60
  2. 获取剩余的秒数。
  3. (可选)将分钟和秒格式化为mm:ss.
索引.js
const totalSeconds = 565; // 👇️ get number of full minutes const minutes = Math.floor(totalSeconds / 60); // 👇️ get remainder of seconds const seconds = totalSeconds % 60; function padTo2Digits(num) { return num.toString().padStart(2, '0'); } // ✅ format as MM:SS const result = `${padTo2Digits(minutes)}:${padTo2Digits(seconds)}`; console.log(result); // 👉️ "09:25"

第一步是通过将秒数除以
60并将结果向下舍入来获得完整的分钟数。

如果数字有小数,则Math.floor函数将

数字向下舍入,否则按原样返回数字。

索引.js
console.log(Math.floor(9.99)); // 👉️ 9 console.log(Math.floor(9.01)); // 👉️ 9 console.log(Math.floor(9)); // 👉️ 9
This ensures that we don’t get values with a decimal, e.g. 9.416 for the minutes. If the value has a decimal, we want to show the seconds and hide the decimal.

We used the modulo (%) operator to get the remainder of seconds.

index.js
const totalSeconds = 565; // 👇️ get remainder of seconds const seconds = totalSeconds % 60; console.log(seconds); // 👉️ 25

When we divide totalSeconds by 60, we get a remainder of 25 seconds.

In other words, once we subtract all the full minutes from totalSeconds, we have 25 seconds left.

The next step is to format the minutes and seconds as mm:ss, e.g. 05:45.

Our padTo2Digits function, takes care of adding a leading zero if the minutes
or seconds only contain a single digit (are less than 10).

index.js
function padTo2Digits(num) { return num.toString().padStart(2, '0'); } console.log(padTo2Digits(1)); // 👉️ '01' console.log(padTo2Digits(5)); // 👉️ '05' console.log(padTo2Digits(10)); // 👉️ '10'

We want to make sure the result doesn’t alternate between single and double
digit values depending on the minutes and seconds.