How to convert a date string (YYYYMMDD) to a date with JavaScript?

Sometimes, we want to convert a date string (YYYYMMDD) to a date with JavaScript.

In this article, we’ll look at how to convert a date string (YYYYMMDD) to a date with JavaScript.

How to convert a date string (YYYYMMDD) to a date with JavaScript?

To convert a date string (YYYYMMDD) to a date with JavaScript, we can call the JavaScript string’s substring method to extract the year, month, and day from the string.

Then we can use the Date constructor to convert it to a JavaScript date.

For instance, we write:

const dateString = "20200515";
const year = +dateString.substring(0, 4);
const month = +dateString.substring(4, 6);
const day = +dateString.substring(6, 8);

const date = new Date(year, month - 1, day);
console.log(date)

to call substring to extract the year, month and day substrings from the dateString.

Then we use the unary + operator to convert the strings to numbers.

Next, we use the Date constructor with year, month - 1 and day to create the date from the substrings.

We’ve to subtract month by 1 since JavaScript month starts with 0 for January.

Therefore, date is:

Fri May 15 2020 00:00:00 GMT-0700 (Pacific Daylight Time)

Conclusion

To convert a date string (YYYYMMDD) to a date with JavaScript, we can call the JavaScript string’s substring method to extract the year, month, and day from the string.

Then we can use the Date constructor to convert it to a JavaScript date.