📜 ⬆️ ⬇️

Implicitly setting the value of a Date object?

Task: to get yesterday and day_week_jack on javascript. I write a simple script:
var dateToday = new Date();
var tmpDate = new Date();

tmpDate.setDate(dateToday.getDate() - 8);
alert(dateToday); // <- Jun 07, OK
alert( tmpDate ); // <- May 30, OK

tmpDate.setDate(dateToday.getDate() - 1);
alert(dateToday); // <- Jun 07, OK
alert( tmpDate ); // <- May 06, Oooops!


It would seem that there is something special? Let's see what I wanted and what I got:
- I create two different Date objects and write them into the dateToday and tmpDate variables. Now here is "today";
- Set tmpDate value to (dateToday - 8 days), i.e. if today is June 7th, then it turns out on May 30th, that's right. Displays the value of tmpDate - indeed, on May 30;
- Now I want to get yesterday. I take the dateToday value (it has not changed anywhere and keeps the day today) and subtract 1 day from it. I have to get June 6th;
- Alert displays May 5th!

What is the reason for such a strange script behavior? And the fact that the Date object has properties has day, month, year, hour, etc. are not interconnected in any way, so the first installation set the month = 5, the day = 30, and the second - only the day = 5. From here we get May 5th.

What to do? Re-initialize the variable before the second action. Those.:
var dateToday = new Date();
var tmpDate = new Date();

tmpDate.setDate(dateToday.getDate() - 8);
alert(dateToday); // <- Jun 07, OK
alert( tmpDate ); // <- May 30, OK

tmpDate = new Date();

tmpDate.setDate(dateToday.getDate() - 1);
alert(dateToday); // <- Jun 07, OK
alert( tmpDate ); // <- Jun 06, OK!


For me it was a completely unobvious thing, spent half an hour of precious time;)

')

Source: https://habr.com/ru/post/95758/


All Articles