// Определим текущий месяц и год var month = parseInt(new Date().getMonth()); var year = new Date().getFullYear(); // Определим количество дней в месяце var total_days = 32 - new Date(year, month, 32).getDate(); console.log(total_days); 

It works correctly, but what happens? How does the line work where var total_days = do not understand at all, find out the date on the 32nd day?

  • when you use the number of days more than the days in the month, it jumps to the next month, respectively, if there are 30 days in the month new Date (year, month, 32) .getDate (); will return - 2, if 31 - 1 and so on. And to find out how many days this month are simply subtracted from 32 - Jbyh

3 answers 3

The work of magic is based on the fact that if the number of days is transferred to the date constructor in more than the current month, the date is automatically spent next month.

I.e

 new Date(2017, 7, 33) 

Will not return on August 33 and the second of September.

getDate() will return the day ordinal of the month, respectively . That is, 2 - for the second of September, 1 - for the first.

Accordingly, transferring 32 to the constructor dates for the month with 30 days - we will come to the second number, for the month with 31 days - to the first. With 28 days - on the fourth. This number and subtract.

Accordingly, this magic is tied to the non-obvious (although described in the specification) property of the date constructor, and I would recommend such a generous comment.

  • With days plus days, okay, but when in a non-leap year from March 31 you take away a month - here the fun begins)) - Alexey Shimansky

I suppose that Date (year, month, 32) creates a date next month. If this month was 30 days, then 32 days from the beginning of the current month is the 2nd of the next. If in a month, 31 days is 1 number. Accordingly, getDate () returns the current day, when subtracting from 32, we get 30 or 31 days this month.

    Date takes 3 parameters - year, month and day of the month. To transfer the day of the month more than it is in the specified month, then the Date will automatically add the new month (as if the number of days were transferred from the beginning of the month).

    Ie for example 2017-01-32 - will be 2017-02-01 and 2017-02-32 - will be 2017-03-04

    • one
      Date takes 7 parameters :-) - Grundy