-1

So I have a time array which holds slot time. I am trying to convert 12 hr format to 24 hr format but it is not working

Here is what I have tried so far:

let timeArray = ["11:12 AM", "11:13 AM", "1:14 PM"];
for (i in timeArray) {
  let [time, mod] = timeArray[i].split(" ");
  let [hr, min] = time.split(":");
  if (hr < 12) {
    hr = hr + 12;
  }
  console.log(hr);
}

Here is the output:

enter image description here

The expected output should add 12 to hr number to convert it to 24 hr format.

Penny Liu
  • 11,885
  • 5
  • 66
  • 81
Gunal Bondre
  • 64
  • 1
  • 10

2 Answers2

0

I would suggest you use moment.js ( https://momentjs.com/ ) You can play with date and time object in numerous way you want by using moment.js

Akshar Sarvaiya
  • 220
  • 2
  • 7
-1

Use parseInt to convert the string to an integer.

let timeArray = ["11:12 AM", "11:13 AM", "1:14 PM"];
for (i in timeArray) {
  let [hr, min] = timeArray[i].split(":");
  if (hr < 12) {
    hr = parseInt(hr) + 12;
  }
  console.log(hr);
}
Gerard
  • 14,447
  • 5
  • 28
  • 48