Categories
TypeScript Answers

How to check if two dates are in the same day or in the same hour with TypeScript?

Spread the love

Sometimes, we want to check if two dates are in the same day or in the same hour with TypeScript.

In this article, we’ll look at how to check if two dates are in the same day or in the same hour with TypeScript.

How to check if two dates are in the same day or in the same hour with TypeScript?

To check if two dates are in the same day or in the same hour with TypeScript, we can check if their year, month, and date are equal.

For instance, we write

const sameDay = (d1, d2) => {
  return (
    d1.getFullYear() === d2.getFullYear() &&
    d1.getMonth() === d2.getMonth() &&
    d1.getDate() === d2.getDate()
  );
};

to create the sameDay function that gets the year of each date with getFullYear.

getMonth gets the month, and getDate gets the date of the month.

Then we compare all 3 and join them with && to check if both dates have the same year, month, and date.

Conclusion

To check if two dates are in the same day or in the same hour with TypeScript, we can check if their year, month, and date are equal.

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 *