在C ++中将时间从24小时制转换为12小时制

在本教程中,我们将讨论将时间从24小时制转换为12小时制的程序。

为此,我们将提供24小时格式的特定时间。我们的任务是将其转换为带有“ AM”或“ PM”扩展名的12小时格式。

示例

#include <bits/stdc++.h>
using namespace std;
//转换为12小时格式
void convert_12hour(string str){
   int h1 = (int)str[0] - '0';
   int h2 = (int)str[1] - '0';
   int hh = h1 * 10 + h2;
   //找到扩展名
   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