Borislav Hadzhiev
Sat Jan 22 2022·2 min read
Photo by Farsai Chaikulngamdee
To convert YYYY-MM-DD
to MM/DD/YYYY
format:
split()
method to split the string on each hyphen.month
, day
and year
to an array.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.
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.
// 👇️ "09/24/2022" console.log(['09', '24', '2022'].join('/'));
You could also use a template literal to achieve the same result.
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.
function padTo2Digits(num) { return num.toString().padStart(2, '0'); } console.log(padTo2Digits(2)); // 👉️ '02' console.log(padTo2Digits(4)); // 👉️ '04' console.log(padTo2Digits(10)); // 👉️ '10'
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).
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.