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

Storing a time_point outside of the application


I am using an std::chrono::system_clock::time_point in my program. When the application stops I want to save to the time_point to a file and load it again when the application starts.

If it was an UNIX-Timestamp I could simply store the value as integer. Is there a way to similarly store a time_point?


Solution

  • Yes. Choose the precision you desire the timestamp in (seconds, milliseconds, ... nanoseconds). Then cast the system_clock::time_point to that precision, extract its numeric value, and print it:

    cout << time_point_cast<seconds>(system_clock::now()).time_since_epoch().count();
    

    Though not specified by the standard, the above line (de facto) portably outputs the number of non-leap seconds since 1970-01-01 00:00:00 UTC. That is, this is a UNIX-Timestamp.

    I am attempting to get the above code blessed by the standard to do what it in fact does by all implementations today. And I have the unofficial assurance of the std::chrono implementors, that they will not change their system_clock epochs in the meantime.

    Here's a complete roundtrip example:

    #include <chrono>
    #include <iostream>
    #include <sstream>
    
    
    int
    main()
    {
        using namespace std;
        using namespace std::chrono;
    
        stringstream io;
        io << time_point_cast<seconds>(system_clock::now()).time_since_epoch().count();
    
        int64_t i;
        system_clock::time_point tp;
        io >> i;
        if (!io.fail())
            tp = system_clock::time_point{seconds{i}};
    }