Y
Y
YakutD2021-12-03 16:40:03
JavaScript
YakutD, 2021-12-03 16:40:03

Why does JS change the date?

I get a date from a form as a string like this:
Then I create a Date object from that string. When I debug, I see that the date becomes December 30.
61aa1da41d811779739254.png
Here is the code:

let date = "2021-12-31"
date.setHours(0,0,0,0);
console.log(date);
date = new Date(date);
console.log(date);

Why is this happening? Could it be due to date.setHours? And if so, why didn't the time on the screen reset to zero?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2021-12-03
@bingo347

The date does not change, you just operate with the date in the current time zone (Moscow time), and it is logged to the console in UTCString format, and UTC always uses London time.
Well, the string does not have the setHours method, you must first create a Date object and call this method on it. Although for a date made from such a string, this call is meaningless, since the parameters to be set will be 0 anyway

R
Rsa97, 2021-12-03
@Rsa97

Because the time zones
are 2021-12-31T00:00:00+03:00 === 2021-12-30T21:00:00Z

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question