是否有任何日期/时间功能可以处理明天的日期,包括结转到下个月?

问题描述 投票:0回答:2

我有一个函数需要计算昨天、今天和明天的日期。我使用本地时间来获取今天的日期。我将 1 添加到 tm_mday 以获得明天的日期。问题是如果当前日期是 3/31,如果我将 1 添加到 tm_mday,它将变为 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; 
}
c++ date localtime
2个回答
3
投票

C++中有一个日期包叫chrono。您可以使用它来处理日期和时间计算。

#include <iostream>
#include <chrono>
#include <ctime>

using namespace std;

string get_local_date(const string& s) {
    auto now = chrono::system_clock::now();
    time_t rawtime = chrono::system_clock::to_time_t(now);
    struct tm* timeinfo = localtime(&rawtime);

    if (s == "tomorrow") {
        timeinfo->tm_mday += 1;
    } else if (s == "yesterday") {
        timeinfo->tm_mday -= 1;
    }

    auto modified_time = chrono::system_clock::from_time_t(mktime(timeinfo));
    auto modified_time_t = chrono::system_clock::to_time_t(modified_time);

    char buffer[80];
    strftime(buffer, 80, "%F", localtime(&modified_time_t));
    string str(buffer);

    return str;
}

int main() {
    cout << "Today: " << get_local_date("") << endl;
    cout << "Yesterday: " << get_local_date("yesterday") << endl;
    cout << "Tomorrow: " << get_local_date("tomorrow") << endl;

    return 0;
}

3
投票

(std::)time_t
typically(不是 required to be)表示为自 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;
}

但是,你真的应该使用原生的

<chrono>
库来处理这种东西。它是在 C++11 中引入的。

例如:

#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;
    }
    else if (s == "yesterday") {
        clock -= 24h;
    }

    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);
    */
}
© www.soinside.com 2019 - 2024. All rights reserved.