I want to have a javascript file which checks if current time is between 7pm and 7am. If so it should change the background color on my website to X. If the current time is not between 7pm and 7am the background color should be Y. Since I am new to Javascript I do not know everything, and that's why I need your help!
JavaScript Check if a Date is in the Past setHours(0, 0, 0, 0)) { return true; } return false; }; var past = new Date('2020-05-20'); var today = new Date(); var future = new Date('2030-05-20'); dateInPast(past, today); dateInPast(future, today);
js object is defined as single points in time, durations are defined as a length of time. Durations do not have a defined beginning and end date. They are contextless. A duration is conceptually more similar to '2 hours' than to 'between 2 and 4 pm today'.
Look at the day ( today. getDay() ), if it's 5 (Friday) add 3, if it's 6 (Saturday) add 2, otherwise add 1. Tack on an if statement that says if the date 's day of the week is Saturday, add two more days. Add another if statement to check for Sunday.
var today = new Date().getHours(); if (today >= 7 && today <= 19) { document.body.style.background = "Red"; } else { document.body.style.background = "Blue"; }
See fiddle.
I suggest using a class on the body to manage the style, but handle the classes in JavaScript.
Essentially you'll use the Date class to get the current hour in military time (24 hour). 7 PM is represented as 19 in military time.
var hour = new Date().getHours(); // between 7 PM and 7 AM respectively if(hour >= 19 || hour <= 7) { document.body.className += 'between7'; } else { document.body.className += 'notBetween7'; }
Then in CSS you can handle those classes.
body.between7 { background-color: green; } body.notBetween7 { background-color: red; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With