diff --git a/src/formatDate.js b/src/formatDate.js index 769e27661..b0a32371c 100644 --- a/src/formatDate.js +++ b/src/formatDate.js @@ -7,8 +7,50 @@ * * @returns {string} */ + function formatDate(date, fromFormat, toFormat) { - // write code here + const oldSeparator = fromFormat[3]; + const newSeparator = toFormat[3]; + + const dateParts = date.split(oldSeparator); + const fromParts = fromFormat.slice(0, 3); + const toParts = toFormat.slice(0, 3); + + const resultParts = []; + + for (const part of toParts) { + if (part === 'YY' || part === 'YYYY') { + let yearIndex = fromParts.indexOf('YYYY'); + let yearFormat = 'YYYY'; + + if (yearIndex === -1) { + yearIndex = fromParts.indexOf('YY'); + yearFormat = 'YY'; + } + + let year = dateParts[yearIndex]; + + if (yearFormat === 'YYYY' && part === 'YY') { + year = year.slice(-2); + } + + if (yearFormat === 'YY' && part === 'YYYY') { + if (Number(year) < 30) { + year = `20${year}`; + } else { + year = `19${year}`; + } + } + + resultParts.push(year); + } else { + const index = fromParts.indexOf(part); + + resultParts.push(dateParts[index]); + } + } + + return resultParts.join(newSeparator); } module.exports = formatDate;