I am having some issues displaying data from my backend API because the incoming dates are formatted incorrectly.
Currently, day and month numbers are entered without a preceding '0' if they are less than 10. For example, 9
should be 09
All incoming dates are in this format: year/month/day
.
How can I transform the dates to a format with preceding zeros for numbers less than 10?
My current code:
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));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Tests:
2021/9/14
--> 2021/09/14
2021/1/7
--> 2021/01/07
2021/10/17
--> 2021/10/17
CodePudding user response:
You can easily achieve the result using split, map, and join.
function convertDate(str) {
return str
.split("/")
.map((s) => {
const num = parseInt(s);
return num < 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
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
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')