C++ 时间(而非日期)周期

cat*_*eof 0 c++

我想检查当前时间(在 C++ 中)是否在某个时间范围内。

我想从元组(“12:00”,“17:30”)构造时间范围,即(字符串,字符串)并检查时间 now() 是否在两者之间。

有什么好的方法可以做到这一点吗?我不想检查日期,即我不在乎这一天是星期一还是十月。我只关心时间。

pax*_*blo 5

如果元组中的字符串可以强制为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;
}
Run Code Online (Sandbox Code Playgroud)

使用该函数,您还可以提供一个来查看它是否在给定范围内:

bool isBetween(
    const std::string &now,
    const std::string &lo,
    const std::string &hi
) {
    return (now >= lo) && (now <= hi);
}
Run Code Online (Sandbox Code Playgroud)

并用以下方式调用它:

if (isBetween(getNowHhMm(), lowestTime, highestTime))
    std::cout << "It's in the range.\n';
Run Code Online (Sandbox Code Playgroud)

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";
Run Code Online (Sandbox Code Playgroud)

(a)是的,这是重新发明轮子,但是考虑到这个轮子有多简单,我认为这是一个很好的解决方案。

  • @cateof,正如 42 所说,替代方案类似于 `if ((strcmp(buff, lowerTime) &gt;= 0) &amp;&amp; (strcmp(buff, HighestTime) &lt;= 0)) ...` - 我认为这相当难看C++。 (2认同)