I have this javascript code to schedule when certain divs show, but the problem I'm having is it's not using device time or our time zone. I really need it to be assigned to the central time zone.
function displayMsg() {
var currentTime = new Date();
function toUTC(date) {
return Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds()
);
}
toUTC(currentTime);
var startMsg1Time = new Date("2021-10-03T11:15:00Z");
var endMsg1Time = new Date("2021-10-08T14:33:00Z");
var startMsg2Time = new Date("2021-11-15T23:00:01Z");
var endMsg2Time = new Date("2021-11-16T22:59:59Z");
if (currentTime.getTime() > startMsg1Time.getTime() && currentTime.getTime() <= endMsg1Time.getTime()) {
$('.Msg1').show();
} else if (currentTime.getTime() > endMsg1Time.getTime) {
$('.Msg1').hide();
}
if (currentTime.getTime() > startMsg2Time.getTime() && currentTime.getTime() <= endMsg2Time.getTime()) {
$('.Msg2').show();
} else if (currentTime.getTime() > endMsg2Time.getTime) {
$('.Msg2').hide();
}
}
displayMsg();
As a side note, this isn't completely achieving what I need. I'm trying to have a message show every Sunday from 8:30am-11:15am and Friday from 7:00pm-8:15pm. I was going to use this method and just create a schedule a month at a time, but if anyone can recommend a better approach then I'm happy to hear.
CodePudding user response:
You can do something like in below snippet , i.e , giving only minutes and hour and then checking if day = 1 (Monday)
. I have set alarm time to 11:25 PM
to 11:35 PM
(Monday
) (You can set any)
Use update of alarm according to need , here I have set
1sec
usingsetInterval
Below snippet is for demo only , you can have any number of messages and alarm and specify day of alarm to come up or month (and can be year to which alarm ring)
setInterval(function() {
var d = new Date();
var Msg1Day = d.getDay();
var Msg1TimeStart = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 25, 0, 0)
var Msg1TimeEnd = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 35, 0, 0)
if (Msg1Day === 1) {
if (d >= Msg1TimeStart && d <= Msg1TimeEnd) {
document.querySelector("#demo").innerHTML = "Alarm is ON"
document.querySelector(".Msg1").innerHTML = "You already enjoyed Sunday, It's Monday Time and soon will Be Tuesday(Alarm is from 11:25 PM - 11:35 PM)"
} else {
document.querySelector("#demo").innerHTML = "Alarm is OFF"
document.querySelector(".Msg1").innerHTML = ""
}
} else {
document.querySelector("#demo").innerHTML = "Today is not monday"
}
}, 1000);
<div class="Msg1"></div>
<div id="demo">Alaram status will be in 1sec and will be updated every second</div>