Given a time in 12 hours format, convert it into 24 hours format.
Example
Input: "12:10AM" "12:33PM" Output: 00:10 12:33
We will have to check if the input string in which period of 12 hours format i.e “AM” or “PM” and then accordingly format them.
JavaScript string has method endsWith
which can be used to check if the time is ending with “AM” or “PM”.
Split the time into hours and minutes to easily convert them accordingly based on which period they belong to.
const formatTime = (time) => { //convert the input to lowercase const timeLowerCased = time.toLowerCase(); //split the hours and mins let [hours, mins] = timeLowerCased.split(":"); // Special case // 12 has to be handled for both AM and PM. if (timeLowerCased.endsWith("am")){ hours = hours == 12 ? "0" : hours; } else if (timeLowerCased.endsWith("pm")){ hours = hours == 12 ? hours : String(+hours + 12); } return `${hours.padStart(2, 0)}:${mins.slice(0, -2).padStart(2, 0)}`; }
If the hours or min is having single-digit then they are padded with an extra zero at the beginning.