【问题标题】:How to check if a date is at least one day in the past with momentjs?如何使用momentjs检查日期是否至少过去一天?
【发布时间】:2017-07-01 04:30:24
【问题描述】:

通常如何使用 momentjs 检查随机日期是否至少过去一天(24 小时)?

类似:

const today = moment()
const isAtLeastADayAgo = today.subtract(dateToCheck) > 1 // ??

【问题讨论】:

    标签: javascript jquery date momentjs


    【解决方案1】:

    我建议你使用普通的 javascript Date 构造函数。

    var today =  new Date();
    var pastDate = // some past date
    // 86400 seconds in 24hrs
    // getTime() will return you date in milliseconds
    if(86400000 < today.getTime()-pastDate.getTime()) will return true if past date is older than 24Hrs.
    

    【讨论】:

    • 我的投票,但我会将其编码为if (today - pastDate &gt; 86400000),尽管它在夏令时边界上可能不准确。要解决这个问题:if (pastDate &lt; today.setDate(today.getDate() - 1));-)
    • @RobG 我只是按照 eslint 的建议在右侧写入常量。顺便说一句,我喜欢你的回答(更干净)。
    【解决方案2】:

    您可以简单地使用isBefore

    function isADayAgo(input){
      let yesterday = moment().subtract(1, 'd');
      return input.isBefore(yesterday);
    }
    
    const isAtLeastADayAgo = isADayAgo(moment());
    console.log(isAtLeastADayAgo);
    &lt;script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"&gt;&lt;/script&gt;

    或者您可以使用diff 将粒度限制为天:

    const today = moment();
    const dateToCheck = moment().subtract(3, 'd');
    const isAtLeastADayAgo = today.diff(dateToCheck, 'd') > 1;
    console.log(isAtLeastADayAgo);
    &lt;script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"&gt;&lt;/script&gt;

    【讨论】:

      【解决方案3】:
      const isAtLeastADayAgo = moment().subtract(1,'days')>dateToCheck
      

      【讨论】:

        猜你喜欢
        • 2021-05-17
        • 1970-01-01
        • 1970-01-01
        • 2011-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多