this is my code. I’m try to define a range of hours so that it changes color depending on the moment of the day, but I don’t know how to create a range (e.g. from 7 – 12 -> morning). The problem now is that if I put 3am is says morning when I want it to say night, but, of course, I can’t go over 23 hours to set the night. Could you please help me?
JavaScript
x
45
45
1
import React from "react";
2
import ReactDOM from "react-dom";
3
4
const date = new Date(2021, 1, 1, 3);
5
6
const time = date.getHours();
7
8
let customStyle = {
9
color: ""
10
};
11
12
function getTime() {
13
const morning = time < 12;
14
const afternoon = time < 18;
15
const night = time < 23;
16
17
if (morning) {
18
customStyle = {
19
color: "red"
20
};
21
return "Good morning";
22
} else if (afternoon) {
23
customStyle = {
24
color: "green"
25
};
26
return "Good afternoon";
27
} else if (night) {
28
customStyle = {
29
color: "blue"
30
};
31
return "Good night";
32
}
33
}
34
35
console.log(getTime());
36
37
ReactDOM.render(
38
<h1 className="heading" style={customStyle}>
39
{" "}
40
{getTime()}{" "}
41
</h1>,
42
43
document.getElementById("root")
44
);
45
Advertisement
Answer
You can just define your ranges more precisely with
JavaScript
1
12
12
1
const morning = false;
2
const afternoon = false;
3
const night = false;
4
5
if (time > 7 && time <= 12) {
6
morning = true;
7
} else if (time > 12 && time <= 18) {
8
afternoon = true;
9
} else {
10
night = true;
11
}
12