本文介绍一下如何使用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 }
]
 */

只要传入对应月份的时间戳就可以生成这个月的基础数据了。

希望对你有帮助。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐