將時間從 24 小時制轉換為 12 小時制格式的 C++ 程式
在本教程中,我們將討論將時間從 24 小時制轉換為 12 小時制格式的程式。
為此,我們將提供 24 小時制的一定時間。我們的任務是將其轉換為 12 小時制格式,並加上“AM”或“PM”。
示例
#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;
}輸出
5:35:20 PM
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP