JS: Check if date is less than 1 hour ago?

后端 未结 7 1618
借酒劲吻你
借酒劲吻你 2020-12-13 05:38

Is there a way to check if a date is less than 1 hour ago?

Something like this:



        
7条回答
  •  北荒
    北荒 (楼主)
    2020-12-13 06:02

    Using some ES6 syntax:

    const lessThanOneHourAgo = (date) => {
        const HOUR = 1000 * 60 * 60;
        const anHourAgo = Date.now() - HOUR;
    
        return date > anHourAgo;
    }
    

    Using the Moment library:

    const lessThanOneHourAgo = (date) => {
        return moment(date).isAfter(moment().subtract(1, 'hours'));
    }
    

    Shorthand syntax with Moment:

    const lessThanOneHourAgo = (date) => moment(date).isAfter(moment().subtract(1, 'hours'));
    

提交回复
热议问题