Convert DD-MM-YYYY to YYYY-MM-DD format in JavaScript

avatar

Borislav Hadzhiev

Sat Jan 22 20222 min read

Convert DD-MM-YYYY to YYYY-MM-DD format in JavaScript #

To convert DD-MM-YYYY to YYYY-MM-DD format:

  1. Use the split() method to split the string on each hyphen.
  2. Add the year, month and day to an array.
  3. Join the array elements into a string with a hyphen separator.
index.js
const date = '24-09-2022'; const [day, month, year] = date.split('-'); const result = [year, month, day].join('-'); console.log(result); // 👉️ "2022-09-24"

The first step is to split the DD-MM-YYYY string on each hyphen.

index.js
const date = '24-09-2022'; // 👇️ ['24', '09', '2022'] console.log(date.split('-'));

The split method returns an array of substrings.

The last thing we have to do is add the year, month and day values to an array and join them into a string with a hyphen separator.

index.js
// 👇️ "2022-09-24" console.log(['2022', '09', '24'].join('-'));

Alternatively, you can use a template literal to achieve the same result.

index.js
const date = '24-09-2022'; const [day, month, year] = date.split('-'); const result = `${year}-${month}-${day}`; console.log(result); // 👉️ "2022-09-24"

The dollar sign curly braces ${} part is an expression that gets evaluated and inserted into the string.

If you need to add a leading zero if the month or day are single digit values (less than 10), you can use this padTo2Digits function.

index.js
function padTo2Digits(num) { return num.toString().padStart(2, '0'); } console.log(padTo2Digits(3)); // 👉️ '03' console.log(padTo2Digits(6)); // 👉️ '06' console.log(padTo2Digits(10)); // 👉️ '10'

It only ads a leading zero if the length of the passed in value is less than 2. This would format the values consistently if your month or day are single-digit strings.

You can use the same approach to convert a DD/MM/YYYY string to YYYY/MM/DD.

index.js
const date = '24/09/2022'; const [day, month, year] = date.split('/'); const result = [year, month, day].join('/'); console.log(result); // 👉️ "2022/09/24"

All we had to do is change the separator to a forward slash / when splitting and joining the date strings.

Use the search field on my Home Page to filter through my more than 1,000 articles.