javascript - 在JS / node /moment中检查某个日期的午夜和当前时刻之间的间隔
问题描述
我有一个 JS Date 对象(例如09.08.2020 15.45
),并且想写一个表达式“当前时刻在下一个日期的午夜后不到 3 分钟”(所以它是true
从09.09.2020 00:00
直到的时间09.09.2020 00:03
,否则为假)。
什么是最佳、最优雅的表达方式?我可以使用任何 npm 包,例如moment
.
解决方案
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);
}
推荐阅读
- notepad++ - 查找相同的单词,但在不同的文件中替换为不同的单词
- node.js - 无法从 Alamofire 向 ExpressJs 发送 POST 请求
- javascript - 有没有办法复制没有唯一 id 或类的元素?
- android - ConstraintLayout 中的 TextView 导致父级缩小
- javascript - 合并两个数组javascript
- javascript - 显示/隐藏按钮的条件渲染 - ReactJs
- apollo - Apollo GraphQL 取消订阅似乎坏了
- ios - iOS 13 检查 CLLocationManager 的临时授权状态
- android - 我怎样才能找到 Skobbler 库的 x64 库?
- ruby-on-rails - rails image_path 呈现绝对路径