一、JavaScript中获取月的天数。
在不使用任何工具包的情况下,如何解决这一问题。
var nowDate = new Date();
1. 先判断当前年是不是闰年,在判断当前月是第几月,返回天数。
代码不想写,也比较简单,:) :) :) :) :)。对于这一答案我很欣慰。
2. 我坚信一句,不论是什么技术,只要是市场成熟的,你考虑的都是多余的。虽然这句话是我说的,不是全对。
好了,分析JavaScript Date MDN
由于本需求和具体的日期有关,重点查看getDate(),setDate()方法的文档说明。在setDate()方法中:
If the dayValue is outside of the range of date values for the month, setDate() will update the Date object accordingly. For example, if 0 is provided for dayValue, the date will be set to the last day of the previous month.
大概意思是:如果dayValue指定为0,那么日期就会被设置为上个月的最后一天。
例子:
var theBigDay = new Date(1962,6,0);
//1962-06-30;
至于月份的问题这里不做分析,实际月份要+1,代码月份是(0-11),实际月份是(1-12)。
方法封装
function getMonthDayNumber(year, month){
return new Date(year, month, 0).getDate();
}3. moment.js 中的实现。
在成熟的操作日期的辅助库中,也有这样的实现。
直接看源码

在moment.js 中,this是以当前日期封装的对象。