2
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
    var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

Can Somebody please explain this code why we give 1 in firstDay and in and +1,0 in the lastDay What it will do..... I know it will give first date and last date i need why we are using that...

str
  • 42,689
  • 17
  • 109
  • 127
ashbaq1
  • 45
  • 1
  • 8

2 Answers2

1

JavaScript's Date object is quite smart in terms of handling invalid days/months: It lets you specify invalid days, months, etc., and handles it by "wrapping" to the next/previous month, year, etc.

So in the above, this line:

var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

...creates a date for the next month (date.getMonth() + 1), but day 0 of that month. Days start from 1, not 0, so the Date object figures out that it's supposed to go back one day — which gives you the end of the previous month.

In that example, the Date constructor uses the specification's abstract operation MakeDay, which defines this behavior.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

This is one of the constructors we use in JavaScript for Date.

new Date(year, month, day, hours, minutes, seconds, milliseconds)

So the 1 in the first statement sets the day to 1.

As for the second statement, the getMonth() function returns values from 0 to 11. So when we do a getMonth() + 1, we make it go to the next month. And then when we use the day argument as 0, we force it to shift back to the last day of the previous month.

Aditya Gupta
  • 633
  • 1
  • 4
  • 11