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

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

希望对你有帮助。

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值