12h to 24h Time Conversion

Easy~10 min

Convert a time string from 12-hour format to 24-hour format.

Input format: "hh:mm AM" or "hh:mm PM" (hours may be 1 or 2 digits, e.g., "1:30 PM" or "12:00 AM").

Output format: "HH:MM" in 24-hour time (always 2-digit hours with leading zero if needed).

Rules:

  • 12:00 AM is midnight, which is "00:00" in 24-hour time
  • 12:30 PM stays "12:30"
  • 1:00 PM becomes "13:00"
  • 12:00 PM is noon, which stays "12:00"
  • AM hours (1-11) keep their value; PM hours (1-11) have 12 added

Examples

Example 1
Input: time = "12:00 AM"
Output: "00:00"
Explanation: 12 AM (midnight) converts to 00:00 in 24-hour format.
Example 2
Input: time = "1:30 PM"
Output: "13:30"
Explanation: 1 PM + 12 = 13, so 1:30 PM becomes 13:30.
Example 3
Input: time = "12:00 PM"
Output: "12:00"
Explanation: 12 PM (noon) stays as 12:00 in 24-hour format.

Constraints

  • Input is a valid 12-hour time string in the format "h:mm AM" or "hh:mm AM" (or PM)
  • Hours range from 1 to 12, minutes from 00 to 59
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run