比较12小时的格式时间

时间:2017-05-05 20:01:25

标签: c++

我必须先计算当天首先出现的时间 输入格式类似于上午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;
}

此代码是通用的,并且始终提供正确的输出。 但由于此代码相当冗长且包含大量比较,无论如何我可以缩短此代码吗?

3 个答案:

答案 0 :(得分:2)

如果您认为格式总是像09:35AM而不是9:35AM,那么以下代码也可以使用。请注意,第5个字符是最重要的区别,我们可以利用'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]);
}

答案 1 :(得分:0)

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

#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";
  }
}

答案 2 :(得分:0)

对于这样的问题,请使用标准库:

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));
}

免责声明:我做了一些测试,事实证明&#34;%p&#34;不作为documented工作。所有其他格式参数都正常工作。 这是一个example