Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion src/formatDate.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,39 @@
* @returns {string}
*/
function formatDate(date, fromFormat, toFormat) {
// write code here
const dateParts = date.split(fromFormat.at(-1));

const day = dateParts[fromFormat.indexOf('DD')];
const month = dateParts[fromFormat.indexOf('MM')];
const year =
dateParts[fromFormat.indexOf('YYYY')] ||
dateParts[fromFormat.indexOf('YY')];

return toFormat
.map((format) => {
switch (format) {
case 'DD':
return day;
case 'MM':
return month;

case 'YYYY':

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The condition year < 100 works by accident for 4-digit years like '2002' (since 2002 is not < 100), but the logic is conceptually flawed. It should check year.length === 2 to determine if conversion is needed, rather than relying on numeric comparison that coincidentally works for some values.

if (year < 100 && year.slice(-2) < 30) {
return '20' + year.slice(-2);
} else if (year < 100) {
return '19' + year.slice(-2);
} else {
return year;
}

case 'YY':
return year.slice(-2);
default:
return '';
}
})
.slice(0, -1)
.join(toFormat.at(-1));
}

module.exports = formatDate;
Loading