OVERVIEW Having some fun by using multiple if and else statements to alter the background and icon displayed based on the time of day. Uses very simple logic that defines daytime as 6am - 6pm.
TIMELINE 2 Hours
Time Now: :
Javascript
var setTime = function() {
var nowDate = new Date(),
nowHours = nowDate.getHours(),
nowMinutes = nowDate.getMinutes(),
amPm,
timeOfDayHTML = document.getElementById("time-of-day"),
hourHTML = document.getElementById("time-hours"),
minHTML = document.getElementById("time-minutes"),
amPmHTML = document.getElementById("time-amPm");
// Convert military time to normal
if (nowHours > 12) {
hourHTML.innerHTML = nowHours - 12;
amPm = 'PM';
} else if (nowHours == 0) {
hourHTML.innerHTML = 12;
amPm = 'AM';
} else {
hourHTML.innerHTML = nowHours;
amPm = 'AM';
}
// Check if its daytime or nighttime
// Daytime is 6am - 6pm
if (nowHours >= 6 && nowHours <= 18) {
timeOfDayHTML.classList.add("its-daytime");
} else {
timeOfDayHTML.classList.add("its-nighttime");
}
// make sure minutes are two digits
if (nowMinutes < 10) {
minHTML.innerHTML = '0' + nowMinutes;
} else {
minHTML.innerHTML = nowMinutes;
}
amPmHTML.innerHTML = amPm;
};
setTime();
HTML
<div id="time-of-day">
<p class="time-goes-here">
<span>Time Now: </span>
<span id="time-hours" class="time-digit"></span>
<span>:</span>
<span id="time-minutes" class="time-digit"></span>
<span id="time-amPm" class="time-digit"></span>
</p>
</div>