JavaScript Convert 12 Hour AM/PM Time to 24 Hour Time Format
We’ll show you how to use JavaScript to convert a 12 hour format to a 24 hour format today. We’ll demonstrate how to convert using a custom function and the Moment.js function.
There are a few more articles on DateTime and Time Zone on this page.
Convert a 12 hour format to 24 hour format
1. Using Moment.js
To use the moment functions, you must include the following moment script.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
To retrieve the converted time, use the JavaScript code below.
var convertedTime = moment("01:00 PM", 'hh:mm A').format('HH:mm')
console.log(convertedTime);
// Output: 13:00
2. Using custom function
We’ll use the following custom JavaScript function to convert the 12 hour format to 24 hour format in this second method.
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}`;
};
var convertedTime = convertTime12to24("01:00 PM");
console.log(convertedTime);
// Output: 13:00
I hope you find this article helpful.
Thank you for reading. Happy Coding..!!