Is it possible to pass a date object as a parameter? I was attempting to set up another set interval to refresh the greeting for automatic updates when I noticed I was using a new Date() a lot. I tried to refactor the code a bit but ended up breaking things. My new code does not recognize the 'today' variable even for the first selector where it was working prior.
//Variables
const today = new Date();
const weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
//Selectors
document.getElementById("day").innerHTML = weekday[today.getDay()];
document.getElementById("date").innerHTML = today.toLocaleDateString();
//Functions
//Greeting based on local time
function timeOfDay(today) {
document.getElementById("greeting").innerHTML =
today.getHours() < 12
? "Good Morning"
: today.getHours() >= 18
? "Good Evening"
: "Good Afternoon";
}
setInterval(timeOfDay, 1000 * 60 * 60);
//Get and display local time
function getTime(today) {
const currentTime = today.toLocaleTimeString();
document.getElementById("time").innerHTML = currentTime;
}
setInterval(getTime, 1);
The code below was working fine I was just trying to see if there was another way to do it without constantly creating a new date object.
//Greeting based on local time
document.getElementById("greeting").innerHTML =
new Date().getHours() < 12
? "Good Morning"
: new Date().getHours() >= 18
? "Good Evening"
: "Good Afternoon";
//Get and display local time
const today = new Date();
const weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
document.getElementById("day").innerHTML = weekday[today.getDay()];
document.getElementById("date").innerHTML = today.toLocaleDateString();
function getTime() {
const time = new Date();
const currentTime = time.toLocaleTimeString();
document.getElementById("time").innerHTML = currentTime;
}
setInterval(getTime, 1);
Any help or advice is appreciated.
The issue here is that when you create a new Date object, its value is the time it was created. It doesn't change after that.
Thankfully there is an easy solution.
You don't need to create a new Date object everytime, just use the object itself as a function.
var now = new Date();
setInterval(() => {
console.log(`new Date(): ${now}`);
console.log(`Date(): ${Date()}`);
console.log("");
}, 1000)