比较12小时格式时间

Comparing 12hour format time

本文关键字:时间 格式 12小时 比较      更新时间:2023-10-16

我必须计算当天首先发生的时间。
输入格式大约是上午12:48。

这是我的比较功能。

string timeCompare(string t1, string t2)
{
    if(t1[5] == 'A' && t1[6]== 'M' && t2[5]=='P')
    {
        return "First";
    }
    else if (t2[5] == 'A' && t2[6] == 'M' && t1[5]=='P')
    {
        return "Second";
    }
    else if (t2[5] == 'A' && t2[6] == 'M' && t1[5]=='A' && t1[6]=='M' )
    {  
        if(stoi(t1)<stoi(t2))
        {
            return "First";
        }
        else if(stoi(t2) == stoi(t1))
        {
            if(t2[3] > t2[3])
            {
                return "Second";
            }
            else if(t2[3] < t1[3])
            {
                return "First";
            }
            else if(t2[3] == t1[3])
            {
                if(t2[4] > t1[4])
                {
                    return "First";
                } 
                if(t1[4] > t2[4])
                {
                    return "First";
                }
                else 
                {
                    return "Equal";
                }
            }
        }
    }
    return 0;
}

此代码是通用的,并且始终提供正确的输出。,但是由于此代码非常漫长并且包含许多比较,无论如何我可以缩短此代码吗?

如果您假定格式始终像09:35AM,而不像9:35AM,则以下代码也应起作用。请注意,第五个字符是最重要的区别,我们可以利用'A' < 'M'的事实。如果该位置在t1t2均等于

string timeCompare(string t1, string t2){
  if(t1[5] < t2[5])
    return "First";
  else if(t1[5] > t2[5])
    return "Second";
  else
    return (t1 < t2) ? "First" : "Second";
}

,如果您将功能的签名更改为返回布尔值,那么代码甚至可以缩短如下:

bool time1LessThanTime2(string t1, string t2){
  return (t1[5] == t2[5]) ? (t1 < t2) : (t1[5] < t2[5]);
}

我会将它们转换为整数(分钟计数(,然后比较:

#include <iostream>
#include <string>
using namespace std;
int timeToInt(const string& t) {
  int hr=stoi(t, nullptr) % 12;
  int min=stoi(t.substr(3),nullptr);
  int time=hr*60+min;
  if (t.at(5)=='p' || t.at(5)=='P') {
    time+=12*60;
  }
  return time;
}
string timeCompare(const string& t1, const string& t2){
  int time1=timeToInt(t1);
  int time2=timeToInt(t2);
  if (time1<time2) {
    return "First";
  } else {
    return "Second";
  }
}

对于此类thins使用标准库:

std::time_t stringToTimeT(const string& s1)
{
    struct std::tm tm {};
    static const auto timeFormat = "%I:%M%p";
    if ((std::istringstream(s1) >> std::get_time(&tm, timeFormat)).eof())
    {
        return mktime(&tm);
    }
    throw std::logic_error("Failed to parse time: "s + s1);
}
double diffTimeFromStrings(const string& s1, const string& s2)
{
    return difftime(stringToTimeT(s1), stringToTimeT(s2));
}

免责声明:我进行了一些测试,事实证明"%p"无法如下记录。所有其他格式参数都可以正常工作。这是一个例子。