Skip to content

Commit

Permalink
Implement format date task
Browse files Browse the repository at this point in the history
  • Loading branch information
galina-palyukh committed Jan 13, 2025
1 parent 67725ad commit 8973024
Showing 1 changed file with 40 additions and 1 deletion.
41 changes: 40 additions & 1 deletion src/formatDate.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,46 @@
* @returns {string}
*/
function formatDate(date, fromFormat, toFormat) {
// write code here
const formatedDate = [];
const datArr = date.split(fromFormat[fromFormat.length - 1]);

const dateObj = {};

for (let i = 0; i < datArr.length; i++) {
if (fromFormat[i].startsWith('Y')) {
dateObj.year = datArr[i];
} else if (fromFormat[i].startsWith('M')) {
dateObj.month = datArr[i];
} else if (fromFormat[i].startsWith('D')) {
dateObj.day = datArr[i];
}
}

const needYearLength = toFormat.find((el) => el.startsWith('Y')).length;

if (dateObj.year.length !== needYearLength) {
const shortYear = dateObj.year.slice(-2);

if (needYearLength === 2) {
dateObj.year = shortYear;
} else {
dateObj.year = shortYear < 30 ? 20 + shortYear : 19 + shortYear;
}
}

const dateSeparator = toFormat.at(-1);

for (const partDate of toFormat) {
if (partDate.startsWith('Y')) {
formatedDate.push(dateObj.year);
} else if (partDate.startsWith('M')) {
formatedDate.push(dateObj.month);
} else if (partDate.startsWith('D')) {
formatedDate.push(dateObj.day);
}
}

return formatedDate.join(dateSeparator);
}

module.exports = formatDate;

0 comments on commit 8973024

Please sign in to comment.