如何将前面的"0"添加到小于 10 的天数和月份



我有一些问题显示数据从我的后端API,因为传入的日期格式不正确。

目前,如果日期和月份小于10,则输入日期和月份时不带前面的"0"。例如,9应为09

所有传入日期格式为:year/month/day.

如何将日期转换为小于10的数字前面有零的格式?

我的当前代码:

let date = '2021/1/31';
const addZeros = (date) => {
const year = date.split('/')[0];
const month = date.split('/')[1];
const day = date.split('/')[2];
return `${year}-${month}-${day}`;
};
console.log(addZeros(date));

测试:

2021/9/14—>2021/09/14

2021/1/7——>2021/01/07

2021/10/17——>2021/10/17

您可以使用分割、映射和连接轻松实现结果。

function convertDate(str) {
return str
.split("/")
.map((s) => (s < 10 ? `0${s}` : s))
.join("/");
}
console.log(convertDate("2021/9/14")); //--> 2021/09/14
console.log(convertDate("2021/1/7")); //--> 2021/01/07
console.log(convertDate("2021/10/17")); //--> 2021/10/17

const addZeros = (date) => {
let [year, month, day] = date.split('/');
month = month.length == 1 ? `0${month}` : month; 
day = day.length == 1 ? `0${day}` : day; 
return `${year}-${month}-${day}`;
};

const test = (date, formatDate) => {
if ( addZeros(date) == formatDate )
console.log("Success!")
else
console.log(`Error: Expected: ${formatDate}, Receive: addZeros(date)`)
}
test('2021/1/31', '2021-01-31')
test('2021/11/1', '2021-11-01')

我用这个简单的方法来添加前导零:

function leadingZeros(n, digitsneeded)
{
return ("00000000000" + n).substr(-digitsneeded)
}
// leadingzeros(3, 2) is "03"
// leadingzeros(12, 5) is "00012"
// leadingzeros(1234, 3) is "234" -- Be careful!

不需要检查是否已经有正确的位数。(但是,它会截断"太大"的字符)。数字,所以要小心。)

相关内容

最新更新