Sometimes, we want to convert 12-hour hh:mm AM/PM time to 24-hour hh:mm time with JavaScript
In this article, we’ll look at how to convert 12-hour hh:mm AM/PM time to 24-hour hh:mm time with JavaScript.
How to convert 12-hour hh:mm AM/PM time to 24-hour hh:mm time with JavaScript?
To convert 12-hour hh:mm AM/PM time to 24-hour hh:mm time with JavaScript, we can manipulate the time strings.
For instance, we write
const convertTime12to24 = (time12h) => {
const [time, modifier] = time12h.split(" ");
let [hours, minutes] = time.split(":");
if (hours === "12") {
hours = "00";
}
if (modifier === "PM") {
hours = parseInt(hours, 10) + 12;
}
return `${hours}:${minutes}`;
};
console.log(convertTime12to24("01:02 PM"));
to define the convertTime12to24
function.
It takes the time12h
string which has the time in 12 hour format.
In it, we split the time12h
string into the time
and modifier
with split
.
Then we split the time
into hours
and minutes
with split
.
Next, we check if hours
is '12'
.
If it is, then we set it to '00'
.
And if modifier
is 'PM'
, we add 12 to the hour.
Finally we return the 24 hour format time string.
Conclusion
To convert 12-hour hh:mm AM/PM time to 24-hour hh:mm time with JavaScript, we can manipulate the time strings.