Search code examples
c++c++11c++-chrono

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


I managed to convert a time point into an integer and write it into a file using code that looks like the following code:

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";

Now I'm trying to read that integer from the file, convert it into a time_point, and print it. Right now, my code looks something like this:

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;

However, it doesn't print anything. Does anyone know where I went wrong?


Solution

  • You have some strange conversions and assign to a variable that you don't use. If you want to store system_clock::time_points as std::time_ts and restore the time_points from those, don't involve other types and use the functions made for this: to_time_t and from_time_t. Also, check that opening the file and that extraction from the file works.

    Example:

    #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);
    
                    // ...
                }
            }
        }
    }