var currentDate = new Date();
var currentY = currentDate.getFullYear();
var currentM = currentDate.getMonth()+1;
var MonthDayNum = new Date(currentY,currentM,0).getDate(); //计算当月的天数
var lastM = new Date(currentY,currentM,0); // new Date(2020,11,0);//表示是2020/12/1号的前一天,就是2020/11/30这天
console.log('当前时间=',currentDate);
console.log('天数=',MonthDayNum);
console.log('当前时间的最后一天日期',lastM);
运行结果:
拓展:
var myDate = new Date();
myDate.getYear(); //获取当前年份(2位)
myDate.getFullYear(); //获取完整的年份(4位,1970-????)
myDate.getMonth(); //获取当前月份(0-11,0代表1月) // 所以获取当前月份是myDate.getMonth()+1;
myDate.getDate(); //获取当前日(1-31)
myDate.getDay(); //获取当前星期X(0-6,0代表星期天)
myDate.getTime(); //获取当前时间(从1970.1.1开始的毫秒数)
myDate.getHours(); //获取当前小时数(0-23)
myDate.getMinutes(); //获取当前分钟数(0-59)
myDate.getSeconds(); //获取当前秒数(0-59)
myDate.getMilliseconds(); //获取当前毫秒数(0-999)
myDate.toLocaleDateString(); //获取当前日期
var mytime=myDate.toLocaleTimeString(); //获取当前时间
myDate.toLocaleString( ); //获取日期与时间
补充
new Date()的参数
1)new Date("month dd,yyyy hh:mm:ss");
2)new Date("month dd,yyyy");
3)new Date(yyyy,mth,dd,hh,mm,ss);
在程序中我使用的第三种初始化方法,总是显示格式化的参数不正确,仔细看了一下一定要是整型的才可以,我传递的是字符串
4)new Date(yyyy,mth,dd);
5)new Date(ms);
需要注意最后一种形式,参数表示的是需要创建的时间和 GMT时间1970年1月1日之间相差的毫秒数。各种函数的含义如下:
month:用英文 表示月份名称,从January到December
mth:用整数表示月份,从(1月)到11(12月)
dd:表示一个 月中的第几天,从1到31
yyyy:四位数表示的年份
hh:小时数,从0(午夜)到23(晚11点)
mm: 分钟数,从0到59的整数
ss:秒数,从0到59的整数
ms:毫秒数,为大于等于0的整数