Reputation: 229
I've been able to show/hide a button if the time is within the range, however, how could I modify this to also check if the date is every second Tuesday, starting on December 1st?
<p id="newButton">LIVE</p>
window.addEventListener("load", function(){
var newButton = document.getElementById("newButton");
const start = 12 * 60 + 30;
const end = 13 * 60 + 30;
const date = new Date();
const now = date.getHours() * 60 + date.getMinutes();
if(start <= now && now <= end) {
newButton.style.display = "block";
alert("in time");
}
else {
newButton.style.display = "none";
alert("offline");
}
}, false);
Upvotes: 0
Views: 193
Reputation: 50807
Here's what I suggested in the comments:
const msPerDay = 24 * 60 * 60 * 1000;
window.addEventListener("load", function(){
var newButton = document.getElementById("newButton");
const start = 12 * 60 + 30;
const end = 13 * 60 + 30;
const date = new Date();
const now = date.getHours() * 60 + date.getMinutes();
if(start <= now && now <= end
&& Math.round((date - 1606798800000) / msPerDay) % 14 === 0) {
newButton.style.display = "block";
alert("in time");
}
else {
newButton.style.display = "none";
alert("offline");
}
}, false);
Note the interesting ambiguity in the question. "Check if the date is every second Tuesday, starting on December 1st?" can be read -- as intended -- to represent alternating Tuesdays. But my initial misreading, "the second Tuesday of any month" is perfectly understandable, if, I suppose, slightly less likely given that the noted start date is itself a Tuesday.
1606798800000
is simply the result of new Date('2020-12-01').getTime()
. It's probably a silly optimization not to simply include something like that in the code. So an alternative version might be
if (start <= now && now <= end &&
Math.round((date - new Date(2020, 11, 1).getTime()) / msPerDay) % 14 === 0)
Upvotes: 1