If I console log the date in Node I get the correct date:
console.log(`Date according to Node: ${new Date()}`);
Date according to Node: Mon Apr 04 2022 17:52:20 GMT 0200
However, when I send the date from React via a POST request and console log that date from the req.body
I get:
2022-04-03T22:00:00.000Z
even though when logging the date from the date picker in react to console, I get the correct date! The date I get in console (React) is:
Mon Apr 04 2022 00:00:00 GMT 0200
So, what happens in between that makes req.body.myDate
give me the incorrect date? I can see that my React date has no time, but not sure if that makes a difference in this case.
React:
const onSubmit = async (data, e) => {
var d = new Date(data.visitDate);
d = new Date(
`${d.getFullYear()}-${String(101 d.getMonth()).substr(1)}-${String(
100 d.getDate()
).substr(1)}`
);
try {
const response = await axios.post(
"http://localhost:8000/api/v1/endpoint",
{
email: email,
apptDate: d,
}
);
if (response.status === 201) {
setSuccess(true);
}
} catch (err) {
setSuccess(false);
}
};
CodePudding user response:
It seems that React serializes the date using .toISOString()
when constructing the POST request, and that always gives a date in UTC (with the Z
suffix). Note that 2022-04-03T22:00:00.000Z
is the same point in time as 2022-04-04T00:00:00.000 02:00
.
If you want a point in time at UTC midnight, you must ensure that you create the Javascript Date
as such, e.g., as new Date("2022-04-04")
. By contrast, new Date()
creates a Date in your browser's timezone:
new Date("2022-04-04").toISOString() === '2022-04-04T00:00:00.000Z'
new Date().toISOString() === '2022-04-03T22:00:00.000Z'
if you execute both statements at midnight in your timezone.
To get the current date in React, you can use:
var d=new Date();
new Date(`${d.getFullYear()
}-${String(101 d.getMonth()).substr(1)
}-${String(100 d.getDate()).substr(1)
}`).toISOString()