Convert a 12 hour format to 24 hour format using JavaScript
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.
1 | <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.
1 2 3 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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..!!
working perfectly