比较12小时格式时间
Comparing 12hour format time
我必须计算当天首先发生的时间。
输入格式大约是上午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'
的事实。如果该位置在t1
和t2
均等于
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"无法如下记录。所有其他格式参数都可以正常工作。这是一个例子。
相关文章:
- C++20 标准::时间::d格式的缺点
- 有没有办法使用 Boost 获取区域时间格式?
- 这种日期和时间格式是什么?
- 标准::get_time 中的日期时间格式
- 如何在 NetBeans 模板中更改时间格式
- 升压C 的时期时间/时间格式
- C Unixtimestamp和可读的时间格式
- 语言环境"en_US"中 std::time_get::get_time() 的正确时间格式是什么?
- 如何将存储在字符串变量中的时间转换为时间格式
- 如何将EPOCH时间转换为时间格式(hh:mm)
- 使用C++将任何形式的日期-时间字符串格式更改为美国日期-时间格式
- 如何将浮点数切换为时间格式
- boost::chrono::system_clock - 如何将当前时间格式化为字符串
- 时间格式 HH:MM:SS 输入
- 用C++设置带有小数秒的日期和时间格式
- c++检查有效的日期时间格式
- 将整数转换为时间格式
- c++中的数据和时间格式
- 如何在C++中将日期时间格式从yyyy-MM-dd转换为yyyy/MM/dd
- 使用c++中的strptime将字符串转换为特定的日期时间格式