Jon M. Langel Jon M. Langel - 18 days ago 7
Javascript Question

Removing Zero from Beginning of 24 Hour Time conversion

This is for a problem on Time Conversion from the 12-hour format to the military/24-hour time.

The standard input:

07:05:45PM


The expected output:
19:05:45


The standard/actual output:
019:05:45


The problem lies in the zero ^ at the beginning of the output.

I tried to set the
parseInt()
with a radix of 10 for the decimal numeral system but that didn't have any effect.

This is a result of this following code :

function main() {
var time = readLine();

var hours = parseInt(time.substr(0, 2), 10);
var minutes = parseInt(time.substr(3,5));
var seconds = parseInt(time.substr(6,8));

if ( time.indexOf('AM') !== -1 && hours === 12) {
time = time.replace('12', '00');
}
if (time.indexOf('PM') !== -1 && hours < 12) {
time = time.replace(hours, (hours + 12));
}

time = time.replace(/(AM|PM)/g, '');
console.log(time);
}


Any help would be appreciated!

Answer

You could just rebuild the string instead of using replace. Because you're using replace in your example you're just replacing the 7 with 19. Using replace will also cause issues if you have a time like 12:12:12.

ex.

function main() {
  var time = readLine();

  var hours = parseInt(time.substr(0, 2), 10);
  var minutes = time.substr(3,5);
  var seconds = time.substr(6,8);

  if ( time.indexOf('AM') !== -1 && hours === 12) {
    hours = 0;
  }
  else if (time.indexOf('PM') !== -1 && hours < 12) {
    hours += 12;
  }

  time = (hours < 10 ? "0" + hours : hours) + ':' + minutes + ':' + seconds;
  console.log(time);
}
Comments