VOOZH about

URL: https://www.geeksforgeeks.org/dsa/convert-time-from-24-hour-clock-to-12-hour-clock-format/

⇱ Convert time from 24 hour clock to 12 hour clock format - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert time from 24 hour clock to 12 hour clock format

Last Updated : 2 Aug, 2022

Given a time in a 24-hour clock (military time), convert it to a 12-hour clock format.

Note: Midnight is 00:00:00 on a 24-hour clock and 12:00:00 AM on a 12-hour clock. Noon is 12:00:00 on 24-hour clock and 12:00:00 PM on 12-hour clock.

A string will be given of the format hh:mm: ss and output should be in the format hh:mm: ss AM or hh:mm: ss PM in a 12hour clock. Here hh represents an hour, mm represents minutes and ss represents seconds.

Examples

Input : 17:35:20
Output : 5:35:20 PM
Input : 00:10:24
Output : 12:10:24 AM

The approach to solving this problem requires some observations. First that the minutes and seconds will be the same in both cases. The only change will be in the hours and according to that Meridien will be appended to the string. For hours, first, convert it from string to int datatype, then take its modulo with 12 and that will be our hours in 12-hour format. Still, there will be a case when the hour becomes 00 i.e (12 or 00 in 24-hour format) which we need to handle separately.

Below is the implementation of the above approach: 
 


Output: 
5:35:20 PM

 

Time Complexity: O(8) = O(1)

Auxiliary Space: O(1)

Comment