-1

How to convert 24HR into 12HR in javascript? Supposed I received data in Strings like "9:00 PM". How can I convert it into 21:00 ?

I've already search some threads here, but I can't seem find out the one that matches my case.

  • Your first paragraph describes 2 directions of transformation. Which is the one you are looking for? – trincot Oct 21 '21 at 08:34
  • 2
    Does this answer your question? [Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone](https://stackoverflow.com/questions/13898423/javascript-convert-24-hour-time-of-day-string-to-12-hour-time-with-am-pm-and-no) – Amin Setayeshfar Oct 21 '21 at 08:34
  • so which one do you need? 24 to 12 or 12 to 24? because your questions is contradictory – J_K Oct 21 '21 at 08:36
  • @trincot I'm trying to time format from 24h to 12h. – John Phillip Abello Oct 21 '21 at 08:36
  • @AminSetayeshfar that thread accepts a 12hr parameter. I need to convert "09:00 PM" into "21:00". So instead , I will have to supply a 24H string into a function. – John Phillip Abello Oct 21 '21 at 08:38
  • Then why do you ask *"how can I convert it into 21:00"*? That is 12h to 24h... It seems you call AM/PM format the 24h format, but that is the 12h format, and vice versa. – trincot Oct 21 '21 at 08:45
  • Any way, conversions in both directions have been asked before. – trincot Oct 21 '21 at 08:49

2 Answers2

1

I would suggest you to firstly split time in string into hour, minutes and code (am/pm), then use if statement and add 12 if the code==PM

let time = "10:50 PM"
let hour = time.split(" ")[0].split(":")[0]
let mins = time.split(" ")[0].split(":")[1]
let code = time.split(" ")[1]
console.log(hour, code)

let newTime = ""
if (code=="PM") {
    let newHour = Number(hour) + 12
    newTime = newHour + ":" + mins
} else {
    newTime = time.split(" ")[0]
}
console.log(newTime);
dorota
  • 66
  • 2
0

Something like this will help.

const time = "9:00 PM";
const [hour, minute, ampm] = time.split(/[\s:]+/);
console.log(`${+hour + (ampm === "PM" ? 12 : 0)}:${minute}`);
Nitheesh
  • 19,238
  • 3
  • 22
  • 49