时间从12小时制转换为24小时制

时间:2019-12-18 17:21:58

标签: c++

我已经编写了这段代码:

string timeConversion(string s) {
    string time{s[0]}, twelveAM{"12"};
    time+=s[1];

    if((s.find("PM") != string::npos) || ((s.find("AM") != string::npos) && (time.compare(twelveAM)==0)))
        s.replace(s.begin(), s.begin()+2, to_string((stoi(time)+12)%24));

    s.replace(s.end()-2, s.end(), "");
    return s;
}

这里s12:00:00AM时,我的输出是0:00:00,但它应该是00:00:00

一切正常,我将感谢您为解决此问题提供的帮助。

3 个答案:

答案 0 :(得分:2)

我建议研究

之类的库

https://en.cppreference.com/w/cpp/chrono

https://www.boost.org/doc/libs/1_62_0/doc/html/date_time.html

两者都应具有将您的格式转换为其他格式的工具。

根据我的经验,最好不要编写任何日期时间代码,即使是最简单但要使用的库。对此的一种有趣的解释可以在这里找到

https://www.youtube.com/watch?v=-5wpm-gesOY

答案 1 :(得分:1)

如果要打印:cout << to_string((stoi(time)+12)%24) << endl;,您会看到仅替换单个0:

if((s.find("PM") != string::npos) || ((s.find("AM") != string::npos) && (time.compare(twelveAM)==0))){
    cout << to_string((stoi(time)+12)%24) << endl;
    s.replace(s.begin(), s.begin()+2, to_string((stoi(time)+12)%24));
}

给予:

0
0:00:00

您应该只在开头添加第二个零,例如:s.replace(s.begin(), s.begin()+2, "00");

答案 2 :(得分:1)

以下是对库函数不感兴趣的代码更改:

std::stringstream string;
string << std::setfill('0') << std::setw(2) << (stoi(time) + 12) % 24);
s.replace(s.begin(), s.begin() + 2, string.str());