This is a practice interview question related to JS I found online. I have tried to complete it and added code below. My question is would my code be a acceptable answer to the question: Create a function to convert a 'M/D/YYYY' formatted date to a 'YYYYMMDD' formatted date in JS?
function formattedUserDate(userInput) {
const formatDate = userInput
const apiDateForm = formatDate.split('/')
let formatDateMonth = apiDateForm[0]
let formatDateDay = apiDateForm[1]
let formatDateYear = apiDateForm[2]
formatDateMonth.length == 1 ? formatDateMonth = '0' formatDateMonth : null;
formatDateDay.length == 1 ? formatDateDay = '0' formatDateDay : null;
const apiDateFormArray = [formatDateYear, formatDateMonth, formatDateDay];
return apiDateFormArray.join('');
}
console.log(formattedUserDate('5/1/1987'));
CodePudding user response:
function formattedUserDate(userInput) {
const apiDateForm = userInput.split('/')
let formatDateMonth = `0${apiDateForm[0]}`.slice(-2);
let formatDateDay = `0${apiDateForm[1]}`.slice(-2);
let formatDateYear = apiDateForm[2]
const apiDateFormArray = [formatDateYear, formatDateMonth, formatDateDay];
return console.log(apiDateFormArray.join(''));
}
formattedUserDate('5/1/1987')
CodePudding user response:
In Javascript have new method padStart and padEnd has below syntax.
"your_string".padStart(targetLength [,padString]):
function formattedUserDate(userInput) {
const formatDate = userInput
const apiDateForm = formatDate.split('/')
let formatDateMonth = apiDateForm[0]
let formatDateDay = apiDateForm[1]
let formatDateYear = apiDateForm[2]
formatDateMonth = formatDateMonth.padStart(2, "0")
formatDateDay = formatDateDay.padStart(2, "0")
const apiDateFormArray = [formatDateYear, formatDateMonth, formatDateDay];
return console.log(apiDateFormArray.join(''));
}
formattedUserDate('5/1/1987');
CodePudding user response:
I think that may be a correct answer. But your code must be clean and clear like that :)
function formattedUserDate(userInput) {
const date = userInput.split("/");
let day = date[1],
month = date[0],
year = date[2];
return (year formatter(month) formatter(day));
}
const formatter = text => text < 10 ? ('0' text) : text;
console.log("date formatted : " formattedUserDate('5/1/1987'))