我想检查当前时间(在 C++ 中)是否在一个时间范围内。
我想从元组 ("12:00", "17:30") 构造时间范围,即 (string, string) 并检查时间 now() 是否介于两者之间。
有什么好的方法吗?我不想检查日期,即我不在乎是星期一还是十月。我只关心时间。
最佳答案
如果可以将元组中的字符串强制为HH:MM
,则可以使用简单的字符串比较(a)。
下面的完整程序展示了如何获取字符串形式的当前时间:
#include <ctime>
#include <iostream>
std::string getNowHhMm() {
time_t now = time(0);
struct tm *local = localtime(&now);
char buff[sizeof("hh:mm")];
strftime(buff, sizeof(buff), "%H:%M", local);
return buff;
}
int main() {
std::cout << getNowHhMm() << std::endl;
}
使用该函数,您还可以提供一个以查看它是否在给定范围内:
bool isBetween(
const std::string &now,
const std::string &lo,
const std::string &hi
) {
return (now >= lo) && (now <= hi);
}
并调用它:
if (isBetween(getNowHhMm(), lowestTime, highestTime))
std::cout << "It's in the range.\n';
而且,为了提高效率,如果您要检查多个范围,请记住存储 getNowHhMm()
的返回值:
std::string now = getNowHhMm();
if (isBetween(now, "00:00", "05:59"))
std::cout << "It's too early to get up.\n";
else if (isBetween(now, "06:00", "07:59"))
std::cout << "Time to rise.\n";
else if (isBetween(now, "08:00", "11:59"))
std::cout << "Get out of bed, ya lazy slob.\n";
else
std::cout << "Sleep in, you're probably already fired.\n";
(a) 是的,这是在重新发明轮子,但考虑到这个轮子的简单性,我认为这是一个很好的解决方案。
关于C++ 时间(而不是日期)期间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45236225/