This question isn’t WordPress specific so is perhaps better for StackOverflow instead. We can make it WordPress specific by suggesting the use of wp_enqueue_script
to add the script to the page, but ultimately this is a JavaScript question.
I’m basing my answer off of this article
// Get the local time of the visitor
var localTime = new Date();
var localHour = localTime.getHours();
// Bool to determine if it is night or day
var isNight = ( 18 <= localHour || 8 >= localHour ) ? true : false;
// Object containing URL links to images
const backgroundURLs = {
day: 'https://placekitten.com/1960/1960',
night: 'https://placekitten.com/1961/1961',
};
// Sets the background image
const setBackground = (image) => {
// wait for window to be loaded to ensure body is present,
// if you are checking this elsewhere you can remove the window.onload check
window.onload = function() {
document.body.style.background = "url('"+backgroundURLs[image]+"')";
}
};
// Actually set the background based on the bool and URL object.
if ( isNight ) {
setBackground('night');
} else {
setBackground('day');
}