C++ - 仅比较时间

C++ - Comparing only time

本文关键字:时间 比较 C++      更新时间:2023-10-16

有没有办法只比较C++的时间?

例如,给定一个预定义时间数组(字符串,例如"04:00"、"07:00"、"13:00"),我希望能够将当前时间与数组中给出的时间范围进行比较,看看哪个适合。

我已经尝试了strptime但是不断收到未定义的错误。我已经包括了time.hstdio.h.

#include <stdio.h>
#include <ctime>
#include <time.h>
int main() {
//GET CURRENT TIME
time_t now = time(0);
tm *ltm = localtime(&now);
cout << "Time: "<< ltm->tm_hour << ":";
cout << ltm->tm_min << ":";
cout << ltm->tm_sec << endl;
//TRYING TO CONVERT THE TIME FROM STRING TO PROCEED FOR FURTHER COMPARISON
struct tm tm;
std::string s("04:00");
if (strptime(s.c_str(), "%H:%M", &tm)) { //error strptime is undefined
int d = tm.tm_mday,
m = tm.tm_mon + 1,
y = tm.tm_year + 1900;
std::cout << y << "-" << m << "-" << d << " "
<< tm.tm_hour << ":" << tm.tm_min;
}
//ATTEMPT TO DO TIME COMPARISON HERE
}

我错过了任何图书馆吗?

有没有更简单/替代的方法可以做到这一点?

请指导我。谢谢

示例中的时间戳都具有相同的固定格式:两位数小时、冒号、两位数分钟。

这意味着它们完全可以通过std::stringstd::strcmpstd::strncmpstd::memcmpoperator<进行词典比较。