jsは年月によって、入力月は何週間ありますか?

6348 ワード

/**
*                
* @param {string} year
* @param {string} month 1,2,...,12
*/
function getNewWeeks (year, month) {
  var d = new Date()
  d.setFullYear(year, month, 0)
  var monthDays = d.getDate() //     
  var weeks = 0 //     
  //      
  d.setFullYear(year, month - 1, 1) //      
  var w1 = d.getDay() //      (0~6)          
  //               
  if (w1 === 0) {
    //                 
    weeks = 1
    monthDays = monthDays - 1
  } else {
    //                  
    weeks = 1
    monthDays = monthDays - (7 - w1 + 1)
  }
  //         
  d.setFullYear(year, month, 0)
  var newmonthDays = d.getDate()
  d.setFullYear(year, month - 1, newmonthDays) //        
  var w2 = d.getDay() //      (0~6)          
  if (w2 === 0) {
    monthDays = monthDays - 7
  } else {
    monthDays = monthDays - w2
  }
  weeks = weeks + 1 //       
  weeks = weeks + (monthDays / 7) //        
  return weeks
}

console.log(getNewWeeks(2020, 8)) // 6