JavaScript 中将秒转换为分秒
JavaScript 中将秒转换为分钟和秒:
- 通过将秒数除以 60 得到整分钟数。
- 获取剩余的秒数。
-
或者,将分钟和秒的格式设置为
mm:ss
。
const totalSeconds = 565;
// 👇️ 获取完整分钟数
const minutes = Math.floor(totalSeconds / 60);
// 👇️ 获得剩余的秒数
const seconds = totalSeconds % 60;
function padTo2Digits(num) {
return num.toString().padStart(2, '0');
}
// ✅ 格式化为 MM:SS
const result = `${padTo2Digits(minutes)}:${padTo2Digits(seconds)}`;
console.log(result); // 👉️ "09:25"
第一步是通过将秒数除以 60 并将结果向下舍入来获得完整的分钟数。
如果数字有小数,则 Math.floor
函数将数字向下舍入,否则按原样返回数字。
console.log(Math.floor(9.99)); // 👉️ 9
console.log(Math.floor(9.01)); // 👉️ 9
console.log(Math.floor(9)); // 👉️ 9
这确保我们不会得到带小数的值,例如 9.416 分钟。 如果该值有小数,我们希望显示秒并隐藏小数。
我们使用模 %
运算符来获取剩余的秒数。
const totalSeconds = 565;
// 👇️ get remainder of seconds
const seconds = totalSeconds % 60;
console.log(seconds); // 👉️ 25
当我们将 totalSeconds
除以 60 时,我们得到 25 秒的余数。
换句话说,一旦我们从
totalSeconds
中减去所有完整的分钟数,我们还剩下 25 秒。
下一步是将分钟和秒格式化为 mm:ss
,例如 05:45。
如果分钟或秒仅包含一个数字(小于 10),我们的 padTo2Digits
函数会负责添加前导零。
function padTo2Digits(num) {
return num.toString().padStart(2, '0');
}
console.log(padTo2Digits(1)); // 👉️ '01'
console.log(padTo2Digits(5)); // 👉️ '05'
console.log(padTo2Digits(10)); // 👉️ '10'
我们希望确保结果不会根据分钟和秒数在一位数和两位数值之间交替。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。