js 获取每个月的第一天和最后一天日期

本文介绍了如何使用JavaScript编写函数来获取指定日期的月初和月底,包括getMonthFirstDay()获取月的第一天,getMonthLastDay()获取所求月份最后一天。通过这两个函数,可以轻松处理日期计算问题,如'2021-02-02'的上个月最后一天为'2021-01-31'。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

月第一天

function getMonthFirstDay(date) {
  const myDate = new Date(date)
  const tYear = myDate.getFullYear()
  let tMonth:any = myDate.getMonth() + 1
  // 月份补0
  if (tMonth < 10) {
    tMonth = '0' + tMonth
  }

  return tYear + '-' + tMonth + '-01'
}

月最后一天

取所求月份的下一个月第一天,减去一天即为所求月份最后一天

function getMonthLastDay(date) {
  const myDate = new Date(date)
  const tYear = myDate.getFullYear()
  let tMonth = myDate.getMonth() + 1
  const nextMonth = tMonth % 12 + 1
  // 下个月第一天
  const nextMonthFirstDay = tYear + '-' + nextMonth + '-01'
  // 减去一天
  const lastDate = new Date(nextMonthFirstDay).getTime() - 1000 * 60 * 60 * 24
  const tDay = new Date(lastDate).getDate()
  // 月份补0
  if (tMonth < 10) {
    tMonth = '0' + tMonth
  }

  return tYear + '-' + tMonth + '-' + tDay
}

getMonthLastDay('2021-02-2') //'2021-02-28'

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值