在 JavaScript 中将 getSeconds() 更改为 2 位数字格式
要将 getSeconds()
方法更改为 2 位格式:
-
将调用
getSeconds()
的结果转换为字符串。 -
如有必要,请使用
padStart()
方法添加前导零。 -
padStart
方法允许我们在字符串的开头添加一个前导零。
const date = new Date('March 14, 2025 05:24:07');
const seconds = String(date.getSeconds()).padStart(2, '0');
console.log(seconds); // 👉️ 07
padStart
方法必须在字符串上使用,因此第一步是将秒数转换为字符串。
我们将以下 2 个参数传递给 padStart
方法:
- target length - padStart 方法在填充后应返回的字符串的长度。
- pad string - 我们想要填充现有字符串的字符串,在我们的例子中是 - 0。
我们知道秒的长度应该始终为 2,所以这就是我们设置的目标长度。
如果秒数已经有 2 位数字,则
padStart
方法不会添加额外的前导零,因为我们已将目标长度设置为 2。
const date = new Date('March 14, 2025 13:24:22');
const seconds = String(date.getSeconds()).padStart(2, '0');
console.log(seconds); // 👉️ 22
秒设置为 22(2 位数字),因此 padStart
方法没有添加前导零。
Internet Explorer 不支持 padStart 方法。 如果我们必须支持浏览器,请使用本文介绍的下一种方法。
要将 getSeconds()
方法更改为 2 位格式,请检查秒数是否小于或等于 9,如果是,则使用加法 (+) 运算符向秒数添加前导零,如果不存在 无需添加前导零。
const date = new Date('September 24, 2025 05:24:06');
let seconds = date.getSeconds();
seconds = seconds <= 9 ? '0' + seconds : seconds;
console.log(seconds); // 👉️ 06
我们使用了一个三元运算符,它与 if/else
语句非常相似。
如果秒数等于或小于 9,我们添加一个前导零,否则我们按原样返回秒数。
两种方法都可以,如果我们必须支持 Internet Explorer,请选择第二种。
相关文章
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 中合并两个数组,以及如何删除任何重复的数组。