Search code examples
c++datedatetimec++-chrono

How to convert epoch count in milliseconds to chrono time_point


I am trying to convert epoch count in milliseconds (e.g., 1699491717000) to a C++ chrono time_point. I have tried the following commands and none of them worked for me.

  1. I tried Howard Hinnant solution but the compiler did not like it

    std::chrono::system_clock::time_point tp{std::chrono::milliseconds{epoch_count_ms}};
    // Compiler says
    // No matching constructor for initialization of 'std::chrono::milliseconds' (aka 'duration<long, ratio<1, 1000>>')
    
  2.  std::chrono::milliseconds epoch_duration(epoch_count_ms);
     std::chrono::system_clock::time_point tp(epoch_duration);
     // Compiler says:
     // No matching constructor for initialization of 'std::chrono::milliseconds' (aka 'duration<long, ratio<1, 1000>>') 
    

Could someone kindly help me out?


Solution

  • epoch_count_ms must be an integral type. If it is a double or a string, it will result in the error message you are seeing.

    The second informational error message after the one you posted should contain this information, e.g.:

    note: candidate constructor (the implicit copy constructor) not viable:
    no known conversion from 'double' to 'const std::chrono::duration<long long, std::ratio<1, 1000>>' for 1st argument class _LIBCPP_TEMPLATE_VIS duration
                              ^^^^^^
    

    This works:

    long long epoch_count_ms = 1699491717000;
    std::chrono::system_clock::time_point tp{std::chrono::milliseconds{epoch_count_ms}};