I am trying to restrict users from seeing certain information on a landing page to only page by comparing if todays date is after Tuesday at 6pm within the current week.
I have been trying to setup this condition but Date/Time functions aren’t my forte.
Using the below I am able to determine the days of the week, but it seems a little buggy in that if within a calendar week a new month starts, the logic resets to the next/previous month.
const today = new Date("2022-11-03 16:20:04");
const first = today.getDate() - today.getDay() + 1;
const tuesday = new Date(today.setDate(first + 1));
const wednesday = new Date(today.setDate(first + 2));
const thursday = new Date(today.setDate(first + 3));
const friday = new Date(today.setDate(first + 4));
console.log('tuesday: ' + tuesday);
const diffTime = Math.abs(tuesday - today);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
console.log(diffDays + " days");
I figured by determining by how many days from monday, I could determine if this had been surpassed or not. Unfortunately, this also doesn’t take into account time, only date as well.
3
Answers
The problem with the code you have is that
setDate
modifies theDate
object on which you call it, so all those calls totoday.setDate
are modifying thetoday
date. To fix the existing code, first copytoday
and then modify the copied object:(Side note: It didn’t used to be reliable to copy
Date
objects as shown above. If you need to support slightly out-of-date browsers, add+
prior totoday
so you havenew Date(+today)
.)But it seems like there’s a simpler way to check if a given date is after 6 p.m. on the current week’s Tuesday:
Live Example:
getDay() on Date gives number of day in a week starting 0(Sunday), 1(Monday), 2 (Tuesday).
getHours() gives hours.
Making sure we crossed 18hrs which is 6pm when day is 2 or day > 2.
If Monday is the first day of the week, a general function to return a particular time on a particular day of the same week as the supplied date can help.
Then just compare the returned date to "now".