Determine if upcoming birthday is within 7 days

Viewed 38

I'm trying to determine whether to show a tag of an upcoming birthday or not by this boolean logic that I'm a bit lost at.

const birthDayDate = new Date('1997-09-20');
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);
const threshold = new Date(today).setDate(today.getDate() + 8);
console.log(birthDayDate >= today && birthDayDate < new Date(threshold));

This is the code piece that I have and would like it to console.log true if an upcoming birthday is within 7 days margin.

Now, given that today and as of writing this post in my timezone it is 09.14.2022, I would like it to console.log the right result which would be true, given that the date we are comparing with is in 6days not taking years into the account.

2 Answers

You are comparing if the birthDayDate is greater than today. How can a day in 1997 be over a day in 2022?

A possible solution is to change the year of the birthDayDate to this year, then check if that date is within 7 days of today:

const birthDayDate = new Date('1997-09-20');
const thisYear = new Date(birthDayDate)
thisYear.setYear(new Date().getFullYear());
const now = new Date();
console.log(thisYear - now <= 1000 * 60 * 60 * 24 * 7 && thisYear - now >= 0);

1000 * 60 * 60 * 24 * 7 is just 7 days in milliseconds.

We also have to check if the date is past today with thisYear - now >= 0.

Try this it also checks if dates are passed after birth date then it will return false.

 const birthDayDate = new Date("1997-09-20");
 const now = new Date();

 const after_threshold = new Date(now.getFullYear(),birthDayDate.getMonth(),birthDayDate.getDate(),0,0,0);

 const before_threshold = new Date(now.getFullYear(),birthDayDate.getMonth(),birthDayDate.getDate() + 8,0,0,0);

 console.log(before_threshold >= now && after_threshold <= now);

Related