I am Trying to use Code to display a Message Depending on the Time of Day
Things i have tried do not work and before anyone says it I want to add a feel to my site and make it More Nice and This is one of the things i want to add
This should get a date with time:
const now = new Date()
const secondsSinceEpoch = Math.round(now.getTime() / 1000)
now.setUTCSeconds(secondsSinceEpoch);
I made an alert
, and localstorage
based message of the day display in pure JavaScript. Hopefully this works, because I didn’t test the code not even once.
function mathrandom(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
} // Just math random function for easy use
var messages = [
"Hello",
"Hi",
"Hey"
]; // Your all messages of the day
var day = new Date().getDate(); // Get day from date
if (localStorage.getItem("NextMessageOfTheDay") === null) { // Does next day exist?
localStorage.setItem("NextMessageOfTheDay", (day + 1).toString()); // Create next day
localStorage.setItem("MessageOfTheDay", messages[mathrandom(0, messages.length)]); // Generate message
alert(localStorage.getItem("MessageOfTheDay")); // Display message
} else {
if (day >= parseInt(localStorage.getItem("NextMessageOfTheDay"))) { // Is this next day?
localStorage.setItem("NextMessageOfTheDay", (day + 1).toString()); // Create next day
localStorage.setItem("MessageOfTheDay", messages[mathrandom(0, messages.length)]); // Generate message
alert(localStorage.getItem("MessageOfTheDay")); // Display message
} else { // If not next day, show the same message
if (localStorage.getItem("MessageOfTheDay") === null) {} else { // If message exists
alert(localStorage.getItem("MessageOfTheDay")); // Display message
}
}
}
If you need explanation for any part of this code, feel free to ask then.
Okay These are both Helpful but not proper answers for the Question i asked
@EddiesTech and @Daw588
When the page loads i want it to read your Computer time and Display a message Based on that time of day like morning,afternoon,Evening and nighttime
Oh I just realized that you are talking about “time” of the “day”, not message of the day. I will modify the code then.
Do you want display completely random message, or you want random message but specifically for that time?
I just want a Specific message to Display at a Specific Times
So morning afternoon and Nighttime
var hours = new Date().getHours();
if(hours >= 0 && hours < 12) {
alert("Good Morning");
} else if(hours >= 12 && hours < 16) {
alert("Good Afternoon");
} else if(hours >= 16 && hours < 21) {
alert("Good Evening");
} else if(hours >= 21 && hours < 24) {
alert("Good Night");
}
To do: Replace
alert
with your own way of displaying messages.
Awww you beat me to it
I mean he is JavaScript after all @khalby786
Yeah, that is true
same
20characters,20