如果输出小于10,我希望它在输出的前面显示0。
const time = new Date();
let hour = today.getHours();
let minute = today.getMinutes();
let second = today.getSeconds();
if (second < 10) {
second = 0 + second;
}
console.log(`Time is ${hour} : ${minute} : ${second}`);
我不想看到19:5:7,而是希望看到19:05:07
///
好的,我发现了问题所在。 0是数字而不是字符串。刚开始使用JS。
感谢您的帮助!
答案 0 :(得分:3)
您可以用前导零填充该值。
const pad2 = s => s.toString().padStart(2, '0');
let today = new Date;
let hour = pad2(today.getHours());
let minute = pad2(today.getMinutes());
let second = pad2(today.getSeconds());
console.log(`Time is ${hour}:${minute}:${second}`);