Convert a 12 hour format to 24 hour format using JavaScript
📅December 1, 2020
Today we’ll show you how to convert a 12 hour format to 24 hour format using JavaScript. Here we will show you the conversion using custom function and Moment.js function.
You will also find the few more articles related to the DateTime and Time Zone.
Convert a 12 hour format to 24 hour format
1. Using Moment.js
First of all, you have to add the following moment script to access the moment functions.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
Use the following JavaScript code to get the converted time.
var convertedTime = moment("01:00 PM", 'hh:mm A').format('HH:mm')
console.log(convertedTime);
// Output: 13:00
2. Using custom function
In the second method, we’ll use the following custom JavaScript function to convert the 12 hour format to 24 hour format.
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
That’s it for today.
Thank you for reading. Happy Coding..!!