【JS时间操作】 js获取n天之后的日期、n月之后的日期、某月最后一天的日期、某周周一和周日的日期

本文提供了一系列JavaScript函数,用于处理日期格式转换、获取指定日期的前后天或月、获取某月最后一天及某周的起始和结束日期等常见需求。

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

首先写一个函数将日期转成你想要的格式

function timeToStr (time) {
  const Y = time.getFullYear() + '-'
  const M = (time.getMonth() + 1 < 10 ? '0' + (time.getMonth() + 1) : time.getMonth() + 1) + '-'
  const D = (time.getDate() < 10 ? '0' + (time.getDate()) : time.getDate()) + ' '
  return Y + M + D
}

 js获取某个日期 n天之后的日期、n月之后的日期:

/* params:
*    startTime --- 指定日期
*    AddCount --- 指定天/月数
*    dayFlag --- true为n天,false为n月
* */
function getDateStr (startTime, AddCount, dayFlag) {
  const dd = new Date(startTime)
  // 获取AddCount天、月后的日期
  if (dayFlag) {
    dd.setDate(dd.getDate() + AddCount)
  } else {
    dd.setMonth((dd.getMonth() - 1) + AddCount)
  }
  return timeToStr(dd)
}

js获取某月最后一天的日期:

function getLastDayOfMonth (time) {
  const dd = new Date(time)
  const curMonth = dd.getMonth()
  //  生成实际的月份: 由于curMonth会比实际月份小1, 故需加1
  dd.setMonth(curMonth + 1)
  // 将日期设置为0, 返回当月最后一天日期, 将日期设置为1,返回下一个月第一天日期
  dd.setDate(0)
  return timeToStr(dd)
}

js获取某周周一和周日的日期:

function getWeekStartAndEnd (time) {
  // 起止日期数组
  let startStop = []
  // 一天的毫秒数
  const millisecond = 1000 * 60 * 60 * 24
  let currentDate = new Date(time)
  // 相对于当前日期AddWeekCount个周的日期
  currentDate = new Date(currentDate.getTime())
  // 返回date是一周中的某一天
  const week = currentDate.getDay()
  // 减去的天数
  const minusDay = week !== 0 ? week - 1 : 6
  // 获得该周的第一天
  const currentWeekFirstDay = new Date(currentDate.getTime() - (millisecond * minusDay))
  // 获得该周的最后一天
  const currentWeekLastDay = new Date(currentWeekFirstDay.getTime() + (millisecond * 6))
  // 添加至数组
  startStop.push(timeToStr(currentWeekFirstDay))
  startStop.push(timeToStr(currentWeekLastDay))
  return startStop
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值