var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
有人可以解释一下这段代码为什么我们在firstDay中提供 1 ,在lastDay中提供 +1,0 它会做什么.....我知道它会给出我需要的第一个日期和最后日期...
答案 0 :(得分:1)
JavaScript的Date
对象在处理无效的日期/月份方面非常聪明:它允许您指定无效的日期,月份等,并通过“包装”到下一个/上个月,年,来处理它等
所以在上面,这一行:
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
...为下一个月(date.getMonth() + 1
)创建日期,但是该月的第0天。天从1开始,而不是0,所以Date
对象表明它应该会在某一天返回 - 这会让你在上个月结束。
在该示例中,Date
constructor使用规范的抽象操作MakeDay
来定义此行为。
答案 1 :(得分:0)
这是我们在JavaScript for Date中使用的构造函数之一。
new Date(year, month, day, hours, minutes, seconds, milliseconds)
因此,第一个语句中的1将日期设置为1。
对于第二个语句,getMonth()
函数返回0到11之间的值。因此,当我们执行getMonth()+ 1时,我们将其转到下个月。然后当我们将day参数用作0时,我们强制它转回上个月的最后一天。