首页 > 解决方案 > 时刻:只要当前时间和日期在请求时间之前最多 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}

标签: javascriptreactjstimemomentjs

解决方案


time1.diff(time2)意味着time1 - time2,因此获得未来日期的否定结果是正确的。

附带说明一下,您现在不需要格式化时间来获取moment对象。

为了得到你想要的结果,这段代码可以工作:

const now = moment();
const requestedTime = moment(details.requestedStartTimestamp);
const diff = requestedTime.diff(now, 'minutes');

if (diff >= 30) {
  // ...
}

推荐阅读