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

avatar

Borislav Hadzhiev

Sat Jan 22 20222 min read

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

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

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

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

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

The split method returns an array of substrings.

The last thing we have to do is add the month, day and year to an array and join them with a forward slash separator.

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

You could also use a template literal to achieve the same result.

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

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(2)); // 👉️ '02' console.log(padTo2Digits(4)); // 👉️ '04' 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.

Here is an example in which the month and day values could possible be single-digit values (less than 10, without a leading zero).

index.js
const date = '2022-9-24'; const [year, month, day] = date.split('-'); const result = [padTo2Digits(month), padTo2Digits(day), year].join('/'); console.log(result); // 👉️ "09/24/2022" function padTo2Digits(num) { return num.toString().padStart(2, '0'); }

Even though the value for the day in the string is a single digit, we got consistent results by using the padTo2Digits function.

Before joining the values into a string, we passed the month and day to the function to add a leading zero if they only contain a single digit.

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