-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
  • 15,447
  • 5
  • 79
  • 98
Gunal Bondre
  • 94
  • 2
  • 12

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
  • 230
  • 2
  • 8
-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
  • 15,418
  • 5
  • 30
  • 52