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?
import React from "react";
import ReactDOM from "react-dom";
const date = new Date(2021, 1, 1, 3);
const time = date.getHours();
let customStyle = {
color: ""
};
function getTime() {
const morning = time < 12;
const afternoon = time < 18;
const night = time < 23;
if (morning) {
customStyle = {
color: "red"
};
return "Good morning";
} else if (afternoon) {
customStyle = {
color: "green"
};
return "Good afternoon";
} else if (night) {
customStyle = {
color: "blue"
};
return "Good night";
}
}
console.log(getTime());
ReactDOM.render(
<h1 className="heading" style={customStyle}>
{" "}
{getTime()}{" "}
</h1>,
document.getElementById("root")
);
Advertisement
Answer
You can just define your ranges more precisely with
const morning = false;
const afternoon = false;
const night = false;
if (time > 7 && time <= 12) {
morning = true;
} else if (time > 12 && time <= 18) {
afternoon = true;
} else {
night = true;
}