乐趣区

关于date:用js获取当前月份的天数

本文介绍一下如何应用 js 获取指定工夫对应月份的天数。

获取以后月份天数

我测试的工夫是 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

如果要获取 2022-02 的天数:

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

留神:new Date() 接管的第三个参数是 0,第二个参数是人类意识中的月份(因为 date.getMonth() 失去的值比设想中的小 1)

补充

月份是从 0 开始计算的:

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

获取指定日期 是 星期几:

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

利用场景

我是在应用 echarts 时遇到了这个问题,须要按月份生成数据:

具备了下面的基础知识,就能够搞定这个问题了:

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}
]
 */

只有传入对应月份的工夫戳就能够生成这个月的根底数据了。

心愿对你有帮忙。

退出移动版