From 86c65de00efdc81da18306fe5264aefae61b3cce Mon Sep 17 00:00:00 2001 From: Oleksandr Polishchuk Date: Thu, 12 Dec 2024 12:20:47 +0200 Subject: [PATCH 1/2] Solution --- src/formatDate.js | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/formatDate.js b/src/formatDate.js index 769e2766..cdf45d97 100644 --- a/src/formatDate.js +++ b/src/formatDate.js @@ -8,7 +8,25 @@ * @returns {string} */ function formatDate(date, fromFormat, toFormat) { - // write code here + const dateParts = date.split(fromFormat[3]); + const result = []; + + result[toFormat.indexOf('DD')] = dateParts[fromFormat.indexOf('DD')]; + result[toFormat.indexOf('MM')] = dateParts[fromFormat.indexOf('MM')]; + + let year = fromFormat.includes('YYYY') + ? dateParts[fromFormat.indexOf('YYYY')] + : dateParts[fromFormat.indexOf('YY')]; + + if (!toFormat.includes('YYYY')) { + year = year.length > 2 ? year.slice(2, 4) : year; + result[toFormat.indexOf('YY')] = year; + } else { + year = year.length === 2 ? (year < 30 ? `20${year}` : `19${year}`) : year; + result[toFormat.indexOf('YYYY')] = year; + } + + return result.join(toFormat[3]); } module.exports = formatDate; From ca2484a4c1cbb005520a1c1a0c1de996dd5177a8 Mon Sep 17 00:00:00 2001 From: Oleksandr Polishchuk Date: Thu, 12 Dec 2024 12:38:37 +0200 Subject: [PATCH 2/2] BetterSolution --- src/formatDate.js | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/formatDate.js b/src/formatDate.js index cdf45d97..1d85677b 100644 --- a/src/formatDate.js +++ b/src/formatDate.js @@ -8,7 +8,18 @@ * @returns {string} */ function formatDate(date, fromFormat, toFormat) { - const dateParts = date.split(fromFormat[3]); + function findSeparator(format) { + for (let i = 0; i < format.length; i++) { + if (!['DD', 'MM', 'YYYY', 'YY'].includes(format[i])) { + return format[i]; + } + } + } + + const separator = findSeparator(fromFormat); + const newSeparator = findSeparator(toFormat); + const dateParts = date.split(separator); + const result = []; result[toFormat.indexOf('DD')] = dateParts[fromFormat.indexOf('DD')]; @@ -26,7 +37,7 @@ function formatDate(date, fromFormat, toFormat) { result[toFormat.indexOf('YYYY')] = year; } - return result.join(toFormat[3]); + return result.join(newSeparator); } module.exports = formatDate;