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.
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.
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);
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}`);