javascript - 时刻:只要当前时间和日期在请求时间之前最多 30 分钟,用户就应该能够执行 X
问题描述
我试着这样做
const currentTime = moment(moment().format('MMMM DD YYYY, h:mm a'));
const timeDifference = moment.duration(currentTime.diff(details.requestedStartTimestamp)).asMinutes();
但我很困惑,因为如果日期是今天或未来日期,timeDifference 显示负数,如果是过去日期,则显示正数,这迫使我添加这个条件:
if(timeDifference <= -30) {执行 x}
解决方案
time1.diff(time2)
意味着time1 - time2
,因此获得未来日期的否定结果是正确的。
附带说明一下,您现在不需要格式化时间来获取moment
对象。
为了得到你想要的结果,这段代码可以工作:
const now = moment();
const requestedTime = moment(details.requestedStartTimestamp);
const diff = requestedTime.diff(now, 'minutes');
if (diff >= 30) {
// ...
}
推荐阅读
- ansible - Ansible OpenShift shell 命令失败,但在 Ansible 之外工作
- ansible - ansible 可以使用列表和字典中的公共值创建字典吗?
- razor - 构建具有 N 列、2 行、容器最大高度的 CSS 网格
- python - 在多个文件/目录中搜索字符串,然后打印文本文件的内容
- reactjs - 功能组件内部应该包含什么
- java - 如何知道一个项目是否是 Spring Boot
- filter - 如何在 Data Studio 的自定义查询中添加过滤器?
- oracle - 在 Oracle 中具有聚合的 NOT HAVING(逆 HAVING)子句
- python - Python:如何处理 glob 和 fnmatch 文件名中的国际字符?
- google-bigquery - 从 Google Cloud Function 调用 BigQuery 时如何节省费用