
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Time from 24-Hour to 12-Hour Format in C++
In this tutorial, we will be discussing a program to convert time from 24 hour clock to 12 hour clock format.
For this we will be provided with certain time in 24 hour format. Our task is to convert it into 12 hour format with the extension of “AM” or “PM”.
Example
#include <bits/stdc++.h> using namespace std; //converting into 12 hour format void convert_12hour(string str){ int h1 = (int)str[0] - '0'; int h2 = (int)str[1] - '0'; int hh = h1 * 10 + h2; //finding the extension string Meridien; if (hh < 12) { Meridien = "AM"; } else Meridien = "PM"; hh %= 12; if (hh == 0) { cout << "12"; for (int i = 2; i < 8; ++i) { cout << str[i]; } } else { cout << hh; for (int i = 2; i < 8; ++i) { cout << str[i]; } } cout << " " << Meridien << '\n'; } int main(){ string str = "17:35:20"; convert_12hour(str); return 0; }
Output
5:35:20 PM
Advertisements