mark mark - 2 months ago 13
Javascript Question

JS AM/PM times always show AM

I am making a simple time calculator in javascript. I have converted the times into 12-hour instead of 24 hour time for simplicity, however the code I have for calculating am/pm always shows am. Any reason why this would be happening?

Here is my code:

function solveTime(x) {
var suffixSolve = (utcHours + x) % 24;
var suffix = "am";
if (utcHours > 12) {
var suffix = "pm";
}
if (utcMinutes == 0) {
utcMinutesLead = "00";
}
if (utcMinutes < 10) {
utcMinutesLead = "0" + utcMinutes;
}
var timeSolve = (((utcHours + x) + 11) % 12 + 1);
var timeTotal = timeSolve + ":" + utcMinutesLead + " " + suffix;
var utcMod = x;
if (utcMod > 0) {
utcMod = "+" + utcMod;
}
document.getElementById(x).innerHTML = "(UTC" + utcMod + ") " + timeTotal;
}


and here is the code behind utcHours

var masterTimeUTC = new Date();
var utcHours = masterTimeUTC.getUTCHours();
var utcMinutes = masterTimeUTC.getUTCMinutes();
var utcSeconds = masterTimeUTC.getUTCSeconds();
var utcMinutesLead = masterTimeUTC.getUTCMinutes();


Example here: http://codepen.io/markgamb/pen/gwGkbo

Answer

The issue is you should be checking whether suffixSolve is greater than 12 instead of utcHours, because utcHours does not change due to the value of x. Since you can shift the hours forward and backwards, I created a variable shift to handle that.

function solveTime(x) {
  if (x < 0) {
    var shift = 24 + x;
  } else {
    var shift = x;
  }

  var suffixSolve = (utcHours + shift) % 24;
  var suffix = "am";
  if (suffixSolve > 12) {
    suffix = "pm";
  }
  if (utcMinutes == 0) {
    utcMinutesLead = "00";
  }
  if (utcMinutes < 10) {
    utcMinutesLead = "0" + utcMinutes;
  }
  var timeSolve = (((utcHours + x) + 11) % 12 + 1);
  var timeTotal = timeSolve + ":" + utcMinutesLead + " " + suffix;
  var utcMod = x;
  if (utcMod > 0) {
    utcMod = "+" + utcMod;
  }
  document.getElementById(x).innerHTML = "(UTC" + utcMod + ") " + timeTotal;
}
var masterTimeUTC = new Date();
var utcHours = masterTimeUTC.getUTCHours();
var utcMinutes = masterTimeUTC.getUTCMinutes();
var utcSeconds = masterTimeUTC.getUTCSeconds();
var utcMinutesLead = masterTimeUTC.getUTCMinutes();
solveTime(4);
solveTime(0);
solveTime(-8);
<div id="4"></div>
<div id="-8"></div>
<div id="0"></div>