Assignment Requirement :
Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.
Note : Midnight is 12:00:00 AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00 PM on 12-hour clock and 12:00:00 on 24-hour clock.
Examples :
Input : 11:21:30 PM Output : 23:21:30 Input : 12:12:20 AM Output : 00:12:20
Approach : Whether the time format is 12 hours or not, can be found out by using list slicing. Check if last two elements are PM, then simply add 12 to them. If AM, then don’t add. Remove AM/PM from the updated time
Python Code
# Python program to convert time
# from 12 hour to 24 hour format
# Function to convert the date format
def convert24(str1):
# Checking if last two elements of time
# is AM and first two elements are 12
if str1[-2:] == "AM" and str1[:2] == "12":
return "00" + str1[2:-2]
# remove the AM
elif str1[-2:] == "AM":
return str1[:-2]
# Checking if last two elements of time
# is PM and first two elements are 12
elif str1[-2:] == "PM" and str1[:2] == "12":
return str1[:-2]
else:
# add 12 to hours and remove PM
return str(int(str1[:2]) + 12) + str1[2:8]
# Driver Code
print(convert24("08:05:45 PM"))
Output :
20:05:45
// C++ program to convert 12 hour to 24 hour
// format
#include<iostream>
using namespace std;
void print24(string str)
{
// Get hours
int h1 = (int)str[1] - '0';
int h2 = (int)str[0] - '0';
int hh = (h2 * 10 + h1 % 10);
// If time is in "AM"
if (str[8] == 'A')
{
if (hh == 12)
{
cout << "00";
for (int i=2; i <= 7; i++)
cout << str[i];
}
else
{
for (int i=0; i <= 7; i++)
cout << str[i];
}
}
// If time is in "PM"
else
{
if (hh == 12)
{
cout << "12";
for (int i=2; i <= 7; i++)
cout << str[i];
}
else
{
hh = hh + 12;
cout << hh;
for (int i=2; i <= 7; i++)
cout << str[i];
}
}
}
// Driver code
int main()
{
string str = "07:05:45PM";
print24(str);
return 0;
} OutPut: 19:05:45 Yes this is a correct output, you can also use this method for problem solving. The first step in exploring seeking study aborad options is to look at your current course schedule and make sure that you can accommodate an extra semester or year. Then, talk to your university's international office or go online to look at the various school's websites and apply through the application process. When your application is accepted, you can choose among the different countries and universities. Before you make this decision, ask your professors which schools they recommend. You can look at rankings online to see how the schools compare, but your professors will be able to give you valuable information about classes and the experience you'll have. Once you've made your choice, you have several more steps to cover before you can head off to your new adventure.