使用 moment.js 获取两个日期之间的所有时间段(并排除一些时间段)(无限循环问题?)

Get all time slots (and exclude some) between two dates using moment.js (infinite loop issue ?)

我是新手,我正在尝试(使用 moment.js)获取两个日期之间的所有时间段,但不包括某些时间段。更准确地说。


const dates = []

const now = moment(now).startOf('day').hour(9).minute(0).seconds(0)
const deadline = moment(end).hour(19).minute(0).seconds(0)    

while (now.diff(deadline) < 0) {
  if (now > now.hour(9)) {
    dates.push(now.format('YYYY-MM-DD HH:mm'))
  }
  now.add(30, 'minutes')
}

没有 if 语句,一切正常(我的数组包含我两个日期之间的所有日期)。但是 if,我的浏览器 崩溃 (无限循环?)。 但我不知道为什么......有什么想法吗?我想学习...

因为 moment 对象是可变的,所以 now.hour(9)(重新)将 hour = 9 设置为 now 实例,因此 now.diff(deadline) < 0 将始终为真。请参阅文档的 Get + Set 部分:

Note: All of these methods mutate the original moment when used as setters.

您可以在 if 条件中克隆 now(使用 clone() 函数或使用 moment(now))。

这是一个活生生的例子:

const dates = []

const now = moment().startOf('day').hour(9).minute(0).seconds(0)
const deadline = moment().hour(19).minute(0).seconds(0) 

while (now.diff(deadline) < 0) {
  if (now > moment(now).hour(9)) {
    dates.push(now.format('YYYY-MM-DD HH:mm'))
  }
  now.add(30, 'minutes');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js"></script>

作为一般规则,不要使用 >< 比较 moment 对象,使用 isAfter, isBefore 等查询方法