是否有任何日期/时间函数可以处理明天的日期(包括结转到下个月)?

Tyl*_*ler 2 c++ date localtime

我有一个函数需要计算昨天、今天和明天的日期。我使用当地时间来获取今天的日期。我将 1 添加到 tm_mday 以获得明天的日期。问题是如果当前日期是 3/31,如果我给 tm_mday 加 1,它就会变成 3/32。C++ 中是否有任何日期包可以处理结转到下个月的问题,或者我需要编写逻辑来执行此操作?

string get_local_date(const string &s) {
    time_t rawtime;
    struct tm * timeinfo;
    time (&rawtime);
    timeinfo = localtime(&rawtime);

    if (s == "tomorrow") {
        timeinfo->tm_mday += 3; // day becomes 3/32
    }
    if (s == "yesterday") {
        timeinfo->tm_mday -= 1;
    }

    char buffer[80];
    strftime(buffer,80,"%04Y-%m-%d",timeinfo);
    string str(buffer);

    return str; 
}
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 6

大多数系统上,(std::)time_t表示为自 POSIX 纪元(1970 年 1 月 1 日 00:00 UTC)以来经过的整数秒数。由于 1 天有 86400 秒(不计算闰秒),您可以简单地为明天添加 86400,并为昨天减去 86400,例如:

#include <string>
#include <ctime>

std::string get_local_date(const std::string &s) {

    std::time_t rawtime = std::time(nullptr);

    if (s == "tomorrow") {
        rawtime += 86400;
    }
    else if (s == "yesterday") {
        rawtime -= 86400;
    }

    char buffer[80] = {};
    std::strftime(buffer, 80, "%04Y-%m-%d", std::localtime(&rawtime));

    return buffer;
}
Run Code Online (Sandbox Code Playgroud)

但是,您确实应该使用 C++11 中引入的本机<chrono>库来处理此类内容,例如:

#include <string>
#include <chrono>
#include <ctime>

std::string get_local_date(const std::string &s) {

    using namespace std::literals::chrono_literals;

    auto clock = std::chrono::system_clock::now();

    if (s == "tomorrow") {
        clock += 24h; // clock += std::chrono::hours(24);
        /* alternatively, in C++20 and later:
        clock += std::chrono::days(1);
        */
    }
    else if (s == "yesterday") {
        clock -= 24h; // clock -= std::chrono::hours(24);
        /* alternatively, in C++20 and later:
        clock -= std::chrono::days(1);
        */
    }

    auto rawtime = std::chrono::system_clock::to_time_t(clock);

    char buffer[80] = {};
    std::strftime(buffer, 80, "%04Y-%m-%d", std::localtime(&rawtime));

    /* alternatively, in C++20 and later:
    return std::format("{:%F}", clock);
    */
}
Run Code Online (Sandbox Code Playgroud)