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

Define

var ONE_HOUR = 60 * 60 * 1000; /* ms */

then you can do

((new Date) - myDate) < ONE_HOUR

To get one hour from a date, try

new Date(myDate.getTime() + ONE_HOUR)                       

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'));

the moment library can really help express this. The trick is to take the date, add time, and see if it's before or after now:

  lastSeenAgoLabel: function() {
    var d = this.lastLogin();
    if (! moment(d).isValid()) return 'danger';  // danger if not a date.
    if (moment(d).add(10, 'minutes').isBefore(/*now*/)) return 'danger'; // danger if older than 10 mins
    if (moment(d).add(5,  'minutes').isBefore(/*now*/)) return 'warning'; // warning if older than 5mins
    return 'success';  // Looks good!
  },

Tags:

Javascript