2

I´m trying to convert a std::chrono::time_point to a long variable and then back to a std::chrono::time_point class. The long variable will be used to send client/server messages on my architecture.

So I have the following test code (code here):

int main ()
{
    std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();

    auto epoch = now.time_since_epoch();
    auto value = std::chrono::duration_cast<std::chrono::milliseconds>(epoch);
    long duration = value.count();

    std::cout << "Duration=" << duration << std::endl;  

    std::chrono::milliseconds ms(duration);

    std::chrono::time_point<std::chrono::system_clock> dt(ms);

    auto epoch1 = dt.time_since_epoch();
    auto value1 = std::chrono::duration_cast<std::chrono::milliseconds>(epoch1);
    long duration1 = value1.count();
    std::cout << "Duration1=" << duration1 << std::endl;  

    if (dt != now)
        std::cout << "Failure." << std::endl;
    else
        std::cout << "Success." << std::endl;
}

As from the output, I have:

Duration=1436221951916
Duration1=1436221951916
Failure.

Why are both durations the same but both times not the same (Failure on comparasion) ? What am I missing here ?

Help appreciated.

Mendes
  • 17,489
  • 35
  • 150
  • 263

1 Answers1

3

Your conversion from std::chrono::time_point to long rounds the time point to milliseconds.

See this question on how properly serialize and deserialize time_points.

Community
  • 1
  • 1
mastov
  • 2,942
  • 1
  • 16
  • 33