Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript if time is between 7pm and 7am do this?

Tags:

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!

like image 792
Yanlu Avatar asked Aug 03 '13 09:08

Yanlu


People also ask

How do you check if the time was in the past in JavaScript?

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);

What is duration in JavaScript?

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'.

How do I get the next working day in JavaScript?

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.


2 Answers

var today = new Date().getHours(); if (today >= 7 && today <= 19) {    document.body.style.background = "Red"; } else {     document.body.style.background = "Blue"; } 

See fiddle.

like image 56
Nev Avatar answered Oct 05 '22 01:10

Nev


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; } 
like image 28
Austin Brunkhorst Avatar answered Oct 05 '22 02:10

Austin Brunkhorst