Categories
JavaScript Answers

How to fix JavaScript’s getDate returns wrong date?

Spread the love

Sometimes, we want to fix JavaScript’s getDate returns wrong date.

In this article, we’ll look at how to fix JavaScript’s getDate returns wrong date.

How to fix JavaScript’s getDate returns wrong date?

To fix JavaScript’s getDate returns wrong date, we use the Date constructor.

For instance, we write

const parseDate = (input) => {
  const [year, month, day] = input.match(/(\d+)/g);
  return new Date(year, month - 1, day);
};

to call input.match to get the parts of a date in an array.

Then we call the Date constructor with the year, month and day.

We subtract month by 1 since Date accepts month number from 0 for January to 11 for December.

Conclusion

To fix JavaScript’s getDate returns wrong date, we use the Date constructor.

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 *