C++ chrono:如何将整数转换为时间点

C++ chrono: How do I convert an integer into a time point

我设法将时间点转换为整数,并使用类似于以下代码的代码将其写入文件:

std::ofstream outputf("data");
std::chrono::time_point<std::chrono::system_clock> dateTime;

dateTime = std::chrono::system_clock::now();

auto dateTimeSeconds = std::chrono::time_point_cast<std::chrono::seconds>(toSerialize->dateTime);
unsigned long long int serializeDateTime = toSerialize->dateTime.time_since_epoch().count();
outputf << serializeDateTime << "\n";

现在我正尝试从文件中读取该整数,将其转换为 time_point,然后打印出来。现在,我的代码看起来像这样:

std::ifstream inputf("data");

unsigned long long int epochDateTime;
inputf >> epochDateTime;
std::chrono::seconds durationDateTime(epochDateTime);
std::chrono::time_point<std::chrono::system_clock> dateTime2(durationDateTime);

std::time_t tt = std::chrono::system_clock::to_time_t(dateTime2);
char timeString[30];
ctime_s(timeString, sizeof(timeString), &tt);
std::cout << timeString;

但是,它不打印任何内容。有谁知道我错在哪里?

撇开日期值错误的可能性不谈,问题出在sizeof(timeString)。看起来你认为它是 30,但它实际上是 char* 的大小,可能是 8(或可能是 4)。

根据ctime_s

the following errors are detected at runtime and call the currently installed constraint handler function:

    buf or timer is a null pointer
    bufsz is less than 26 or greater than RSIZE_MAX 

您进行了一些奇怪的转换并分配给了您不使用的变量。如果您想将 system_clock::time_points 存储为 std::time_ts 并从中恢复 time_points,请不要涉及其他类型并使用为此创建的函数:to_time_tfrom_time_t。另外,检查打开文件和从文件中提取是否有效。

示例:

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

int main() {
    {   // save a time_point as a time_t
        std::ofstream outputf("data");
        if(outputf) {
            std::chrono::time_point<std::chrono::system_clock> dateTime;
            dateTime = std::chrono::system_clock::now();
            outputf << std::chrono::system_clock::to_time_t(dateTime) << '\n';
        }
    }

    {   // restore the time_point from a time_t
        std::ifstream inputf("data");
        if(inputf) {
            std::time_t epochDateTime;
            if(inputf >> epochDateTime) {
                // use epochDateTime with ctime-like functions if you want:
                std::cout << std::ctime(&epochDateTime) << '\n';

                // get the time_point back (usually rounded to whole seconds):
                auto dateTime = std::chrono::system_clock::from_time_t(epochDateTime);

                // ...
            }
        }
    }
}