JavaScript获取日期为2位数字

编写一个示例代码来获取日期中的2位数字。如果日期是个位数就给加上“0”。

获取日期为 2 位数字

要想取得两位数字的日期,需要在日期上加“0”,然后用“slice”取得后两位数字。

let date = new Date('2022-12-5');

// 使用slice(-2)可以获得日期的后两位
console.log( (String(date.getDate())).slice(-2) ); // 5

// 取得后两位数,加上“0”,一位数就是“0x”和“0”,两位数就是“0xx”和三位数。
let day = ("0" + String(date.getDate())).slice(-2);

console.log(day); // 05
console.log(typeof day); // string

date = new Date('2022-12-15');

console.log( (String(date.getDate())).slice(-2) ); // 15

day = ("0" + String(date.getDate())).slice(-2);
console.log(day); // 15

JavaScript获取日期为2位数字

你可以用“padStart”做同样的事情。

let date = new Date('2022-12-5');

let day = String(date.getDate()).padStart(2, '0');
console.log(day); // 05

date = new Date('2022-12-15');

day = String(date.getDate()).padStart(2, '0');
console.log(day); // 15

'slice' 的性能稍好一些。

本文来源:词雅网

本文地址:https://www.ciyawang.com/javascript-date-slice.html

本文使用「 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 」许可协议授权,转载或使用请署名并注明出处。

相关推荐