Categories
JavaScript Answers

How to check if date is less than 1 hour ago with JavaScript?

Spread the love

Sometimes, we want to check if date is less than 1 hour ago with JavaScript.

In this article, we’ll look at how to check if date is less than 1 hour ago with JavaScript.

How to check if date is less than 1 hour ago with JavaScript?

To check if date is less than 1 hour ago with JavaScript, we can compare the timestamp difference to the value for one hour in milliseconds.

For instance, we write

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

  return date > anHourAgo;
};

to define HOUR to be the value of one hour in milliseconds.

Then we use Date.now() - HOUR to get the timestamp in milliseconds for one hour ago.

Finally, we compare the timestamp of date to anHourAgo with

date > anHourAgo

Conclusion

To check if date is less than 1 hour ago with JavaScript, we can compare the timestamp difference to the value for one hour in milliseconds.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *