如何在JavaScript中获取两个日期之间的日期

I had this problem: given two JavaScript Date objects, how can I get a list of the days (expressed as Date objects, too) between those 2 dates?

我遇到了这个问题:给定两个JavaScript Date对象,如何获取这两个日期之间的日期列表(也表示为Date对象)?

Here’s a function to calculate that.

这是一个计算该函数的函数。

It gets 2 date objects as parameters, and returns an array of Date objects:

它获取2个date对象作为参数,并返回一个Date对象数组:

const getDatesBetweenDates = (startDate, endDate) => {
  let dates = []
  //to avoid modifying the original date
  const theDate = new Date(startDate)
  while (theDate < endDate) {
    dates = [...dates, new Date(theDate)]
    theDate.setDate(theDate.getDate() + 1)
  }
  return dates
}

Example usage:

用法示例:

const today = new Date()
const threedaysFromNow = new Date(today)
threedaysFromNow.setDate( threedaysFromNow.getDate() + 3)

getDatesBetweenDates(today, threedaysFromNow)

If you also want to include the start and end dates, you can use this version that adds it at the end:

如果您还希望包括开始日期和结束日期,则可以使用此版本在末尾添加:

const getDatesBetweenDates = (startDate, endDate) => {
  let dates = []
  //to avoid modifying the original date
  const theDate = new Date(startDate)
  while (theDate < endDate) {
    dates = [...dates, new Date(theDate)]
    theDate.setDate(theDate.getDate() + 1)
  }
  dates = [...dates, endDate]
  return dates
}

翻译自: https://flaviocopes.com/how-to-get-days-between-dates-javascript/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值