Categories
JavaScript Answers

How to parse a date in YYYYmmdd format in JavaScript?

Spread the love

Sometimes, we want to parse a date in YYYYmmdd format in JavaScript.

In this article, we’ll look at how to parse a date in YYYYmmdd format in JavaScript.

How to parse a date in YYYYmmdd format in JavaScript?

To parse a date in YYYYmmdd format in JavaScript, we can use some syring methods.

For instance, we write:

const parse = (str) => {
  const y = str.substr(0, 4)
  const m = str.substr(4, 2) - 1
  const d = str.substr(6, 2);
  const date = new Date(y, m, d);
  return (date.getFullYear() === +y && date.getMonth() === +m && date.getDate() === +d) ? date : 'invalid date';
}

console.log(parse('20220202'))

to define the parse function to parse the date string str.

We extract the year y, month m and date d with substr.

And we subtract 1 from m to get a 0-based month required by JavaScript’s Date constructor.

Next, we check if the year, month, and date are all valid with date.getFullYear() === +y && date.getMonth() === +m && date.getDate() === +d.

If that’s true, then we return the date.

Otherwise, we return 'invalid date'.

Conclusion

To parse a date in YYYYmmdd format in JavaScript, we can use some syring methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *