js 非常优雅的获取当月的第一天,最后一天

首先介绍一些基本概念,如下:

const date = new Date() // 获取当前时间的标准格式,Wed May 25 2022 17:02:12 GMT+0800 (中国标准时间),表示2022年5月25日
const year = date.getFullYear() // 获取年,2022
const month = date.getMonth() // 获取月,4(0-11表示1-12月,这里需要注意)
const day = date.getDate() // 获取日,25(1-31)
const oneDay = new Date(year, month, day) // 获取指定时间的标准格式
new Date(2022, 4, 25)等价于new Date('2022-05-25')

再介绍一些基本方法,如下:

const date = new Date()
/**
 * 获取第一天
 */
date.setDate(1)
new Date(year, month, 1)
/**
 * 获取最后一天
 * 值得注意的是,如果day取值为0,意味着取的是date时间的上一个月的最后一天,简单理解:date当前月的第一天,再减去一天
 */
date.setDate(0)
new Date(year, month, 0)
new Date(year, month, new Date(year, month, 0).getDate())

最后实现,如下:

/**
 * 获取本月第一天
 */
const getNowMonthFirst = () => {
	const date = new Date()
  	date.setDate(1)
  	return date
}

/**
* 获取本月最后一天
*/
const getNowMonthLast = () => {
  	const date = new Date()
 	const enddate = new Date(date.getFullYear(), date.getMonth() + 1, 0)
 	return enddate
}

/**
* 获取上月第一天
*/
const getLastMonthFirst = () => {
 	const date = new Date()
 	const firstDate = new Date(date.getFullYear(), date.getMonth() - 1, 1);
  	return firstDate
}

/**
* 获取上月最后一天
*/
const getLastMonthLast = () => {
 	const date = new Date()
 	// 获取上个月的最后一天是几号day
 	const day = new Date(date.getFullYear(), date.getMonth(), 0).getDate()
 	const enddate = new Date(date.getFullYear(), date.getMonth() - 1, day)
  	return enddate
}
或者
const getLastMonthLast = () => {
 	const date = new Date()
 	const enddate = new Date(date.getFullYear(), date.getMonth(), 0)
  	return enddate
}
或者
const getLastMonthLast = () => {
 	const date = new Date()
 	date.setDate(0)
  	return date
}

/**
* 获取指定date所在月的第一天
* 指定时间date形式不限:2022-05-20、2022/05/20...
*/
const getMonthFirst = (date) => {
	const stringDate = new Date(date)
 	const enddate = new Date(stringDate.getFullYear(), stringDate.getMonth(), 1)
 	return enddate
}

/**
* 获取指定date所在月的最后一天
* 指定时间date形式不限:2022-05-20、2022/05/20...
*/
const getMonthLast = (date) => {
	const stringDate = new Date(date)
 	const enddate = new Date(stringDate.getFullYear(), stringDate.getMonth() + 1, 0)
 	return enddate
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值