将时间从 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