如何计算JavaScript中两个日期之间的天数

In particular, I wanted to count the number of nights that a person had to pay to rent a house and sleep in it, depending on the checkin date, and the checkout date.

特别是,我想根据签入日期和退房日期来计算一个人必须租用的房晚并在其中睡觉。

I looked at different solutions, and the one that gave me the least problems, considering all the issues with dates (including DST), was this: starting from the starting date, we add one day until the date represents a date after the end date.

我研究了不同的解决方案,考虑到所有与日期有关的问题(包括DST),该解决方案给我带来最少问题的解决方案是:从开始日期开始,我们加一天,直到该日期表示结束日期之后的日期。

Here’s the code:

这是代码:

const numberOfNightsBetweenDates = (startDate, endDate) => {
  const start = new Date(startDate) //clone
  const end = new Date(endDate) //clone
  let dayCount = 0

  while (end > start) {
    dayCount++
    start.setDate(start.getDate() + 1)
  }

  return dayCount
}

I first clone the dates we are given, because dates are objects, and we get a reference to that object. This means that using setDate() in the function would also affect the variable outside of this function - not something we look forward to!

我首先克隆给定的日期,因为日期是对象,并且获得了对该对象的引用 。 这意味着在函数中使用setDate()也会影响此函数之外的变量-我们不希望看到这种情况!

That’s it.

而已。

If instead you want to get the number of days between 2 dates (say, today to tomorrow is 2 days), just change while (end > start) to while (end >= start). That would work. Or increase the dayCount starting point to 1.

相反,如果要获取两个日期之间的天数(例如,今天到明天是2天),只需将while (end > start)更改为while (end >= start) 。 那行得通。 或将dayCount起始点增加到1

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值