I need to convert the 24-hour time I get from the d.getHours()
function to a 12-hour format while keeping track of AM/PM.
My most recent iteration looks something like this:
// get current date
var date = new Date();
// get current hours
var currentHour = date.getHours();
// for loop counter variable
var i;
console.log("Current hour: " + currentHour);
// used when currentHour + i goes past 24. (25th hour is 0).
resetCounter = 0;
for (i = 1; i < 9; i++) {
// sets variable for spans
var hourlyForecastHours = document.getElementById("hourly" + i);
var hourlyForecastTemp = document.getElementById("hourly-temp" + i);
var hourlyForecastDesc = document.getElementById("hourly-desc" + i);
// first hour to be displayed is currentHour (now) plus i hour.
hour = currentHour + i;
// if currentHour + i is greater than or equal to 24
if (hour >= 24) {
// set hour to 0 + resetCounter
hour = 0 + resetCounter;
// increment resetCounter
resetCounter++;
}
// convert 24 hr time to 12 hr time
hour = hour % 12;
// if hr is 0, make it show 12.
if (hour == "0") {
hour = 12;
}
hourlyForecastHours.textContent = hour;
console.log("Hour + " + i + ": " + hour);
}
This does what I need it to. As of the current hour it outputs "9, 10, 11, 12, 1, 2, 3".
Now I need to keep track of AM/PM. I've tried things such as a variable that is set to "AM" or "PM" if the 24 hour format time is < 12 or >= 12 and then appending that to the end of the converted-to-12-hour time.
I'm getting confused about it all, how can I get this to work?