1.闰年的计算方法。 2.某一月的周数

公历闰年计算方法:

1、普通年能被4整除且不能被100整除的为闰年。(如2004年就是闰年,1900年不是闰年)

2、世纪年能被400整除的是闰年。(如2000年是闰年,1900年不是闰年)

3、对于数值很大的年份,这年如果能整除3200,并且能整除172800则是闰年。

最后一条基本用不到,这样看来,转化成代码就是:

const year = new Date().getFullyear()
year % 4 === 0 && year % 100 !== 0 || year % 400 === 0

补充:闰年有366天,闰年的2月份有29天,平年为365天,2月份为28天。

  所以,可以用二月份的天数来判断是否为闰年

//获取指定月份的天数
const year = 2019 const endTime = new Date(`${year} 03 01 00:00:00`) const startTime = new Date(`${year} 02 01 00:00:00`) console.log(Math.floor((endTime - startTime) / 86400000)) // 28 (二月份的天数)

实例:求指定月份的周数?

  知识点1:每个月的第一天,所在的一整周,为第一周。(比如 2019-09 第一天是周日,那么这一整周都为9月份的第一周)

  知识点2:每个月的最后一周必须是满周的。不满一整周的天数,则不计入这个月份,多出来的天数,计入下一月的第一周。

  getWeeks(value) {
    const year = +value.slice(0, 4);
    const isLeapYear = year % 4 === 0 && year % 100 !== 0 || year % 400 === 0 ? true : false;
    const monthAry = [31, isLeapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    const supplementDay = [6, 0, 1, 2, 3, 4, 5];
    const num = monthAry[+value.slice(5) - 1];    //拿到本月的天数,
    const d = +moment(`${value}-01`).format("d"); //拿到每月的第一天是周几
    const t = supplementDay[d];  //得到第一周需要补全的天数
    const week = Math.floor((num + t) / 7); //得到本月的周数
    console.log(`${value}有${week}周`)
  }
  getWeeks("2019-08")
原文地址:https://www.cnblogs.com/MrZhujl/p/11410535.html