Sometimes, we want to fix JavaScript Date.parse giving incorrect results.
In this article, we’ll look at how to fix JavaScript Date.parse giving incorrect results.
How to fix JavaScript Date.parse giving incorrect results?
To fix JavaScript Date.parse giving incorrect results, we can split the date string into its parts and the use the Date
constructor.
For instance, we write
const parseDate = (input) => {
const [year, month, day] = input.split("-");
return new Date(year, month - 1, day);
};
to create the parseDate
function that splits the input
date string by the dashes.
Then we pass the destructured values from the array into the Date
constructor.
We subtract month
by 1 since JavaScript expects the month to be 0 to 11, with 0 being January and 11 being December.
Finally, we return the created Date
instance.
Conclusion
To fix JavaScript Date.parse giving incorrect results, we can split the date string into its parts and the use the Date
constructor.