首页 > 解决方案 > 在JS / node /moment中检查某个日期的午夜和当前时刻之间的间隔

问题描述

我有一个 JS Date 对象(例如09.08.2020 15.45),并且想写一个表达式“当前时刻在下一个日期的午夜后不到 3 分钟”(所以它是true09.09.2020 00:00直到的时间09.09.2020 00:03,否则为假)。

什么是最佳、最优雅的表达方式?我可以使用任何 npm 包,例如moment.

标签: javascriptnode.jstypescriptmomentjs

解决方案


我会去isBetween。它也可以在day.js中使用

function isLessThanThreeMinutesPastMidnight(date) {
  const nextMidnight = moment().add(1, 'days').startOf('day');
  const threeMinutesPastNextMidnight = moment(nextMidnight).add(3, 'minute');

  return moment(date).isBetween(nextMidnight, threeMinutesPastNextMidnight, null, '[)'); 
}

操场

如果你觉得null, '[)'不是很优雅,你可以考虑使用今天的结束而不是明天的开始:

function isLessThanThreeMinutesPastMidnight(date) {
  const now = moment.now(); // helps to avoid problems with changing the date between `now` calls
  const endOfDay = moment(now).endOf('day');
  const threeMinutesPastNextMidnight = moment(now).add(1, 'days').startOf('day').add(3, 'minute');

  return moment(date).isBetween(endOfDay, threeMinutesPastNextMidnight);
}

推荐阅读