头图
This article introduces how to use js to get the number of days in the month corresponding to the specified time.

Get the number of days in the current month

The time I tested is 2022-09-01:

 const date = new Date()
const year = date.getFullYear()
const month = date.getMonth()

const days = new Date(year,month+1,0).getDate() // 30

If you want to get the number of days in 2022-02:

 const days = new Date(2022,2,0).getDate() // 28

Note: the third parameter received by new Date() is 0, and the second parameter is the month in human consciousness (because the value obtained by date.getMonth() is 1 smaller than expected)

Replenish

Months are counted from 0:

 new Date('2022-01-01 13:55:33').getMonth()
// 0

Get the day of the week for a given date:

 new Date('2022-08-28 13:55:33').getDay()
// 0 星期日(老外喜欢把一周中的星期日当成第一天,也是从0开始)

Application scenarios

I had this problem when using echarts and needed to generate data by month:

With the above basic knowledge, you can solve this problem:

 function genDaysArr(timestamp) {
    const d = new Date(timestamp)
    const y = d.getFullYear()
    const m = d.getMonth()+1
    const m_str = m>10?m:'0'+m

    // 获取指定月份天数
    const days = new Date(y,m,0).getDate()
    const arr = []
    for (let i = 1; i <= days; i ++) {
        const day_str = i>=10?i:'0'+i
        arr.push({day: `${y}-${m_str}-${day_str}`, count: 0})
    }
    return arr
}

const a = genDaysArr(1647852283000)
console.log(a)

/**
[
  { day: '2022-03-01', count: 0 },
  { day: '2022-03-02', count: 0 },
  { day: '2022-03-03', count: 0 },
  { day: '2022-03-04', count: 0 },
  { day: '2022-03-05', count: 0 },
  { day: '2022-03-06', count: 0 },
  { day: '2022-03-07', count: 0 },
  { day: '2022-03-08', count: 0 },
  { day: '2022-03-09', count: 0 },
  { day: '2022-03-10', count: 0 },
  { day: '2022-03-11', count: 0 },
  { day: '2022-03-12', count: 0 },
  { day: '2022-03-13', count: 0 },
  { day: '2022-03-14', count: 0 },
  { day: '2022-03-15', count: 0 },
  { day: '2022-03-16', count: 0 },
  { day: '2022-03-17', count: 0 },
  { day: '2022-03-18', count: 0 },
  { day: '2022-03-19', count: 0 },
  { day: '2022-03-20', count: 0 },
  { day: '2022-03-21', count: 0 },
  { day: '2022-03-22', count: 0 },
  { day: '2022-03-23', count: 0 },
  { day: '2022-03-24', count: 0 },
  { day: '2022-03-25', count: 0 },
  { day: '2022-03-26', count: 0 },
  { day: '2022-03-27', count: 0 },
  { day: '2022-03-28', count: 0 },
  { day: '2022-03-29', count: 0 },
  { day: '2022-03-30', count: 0 },
  { day: '2022-03-31', count: 0 }
]
 */

As long as the timestamp of the corresponding month is passed in, the basic data of this month can be generated.

Hope it helps you.


来了老弟
508 声望31 粉丝

纸上得来终觉浅,绝知此事要躬行