Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solution #2181

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
29 changes: 27 additions & 2 deletions src/formatDate.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,33 @@
*
* @returns {string}
*/
function formatDate(date, fromFormat, toFormat) {
// write code here
function formatDate(date, fromFormat, toFormat, cutoffYear = 30) {

Choose a reason for hiding this comment

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

Consider adding validation to ensure that the date string matches the fromFormat. This will help prevent incorrect conversions or errors if the input format is not as expected.

const fromSeparator = fromFormat[3];
const toSeparator = toFormat[3];
const dateParts = date.split(fromSeparator);
const dateSet = {};

for (let i = 0; i < dateParts.length; i++) {
dateSet[fromFormat[i]] = dateParts[i];
}

const newFormat = [];

for (const key of toFormat) {
if (dateSet[key]) {
newFormat.push(dateSet[key]);
} else if (key === 'YY') {
newFormat.push(dateSet.YYYY.slice(2));
} else if (key === 'YYYY') {
if (dateSet.YY < cutoffYear) {
newFormat.push('20' + dateSet.YY);
} else {
newFormat.push('19' + dateSet.YY);
Comment on lines +28 to +31

Choose a reason for hiding this comment

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

The logic assumes that dateSet.YY is always available, which might not be the case if the input format does not include 'YY'. Consider adding checks to handle scenarios where 'YY' is not part of the fromFormat.

}
}
}

return newFormat.join(toSeparator);
}

module.exports = formatDate;
Loading