Search code examples
c++boost

Current UTC date string with to_iso_extended_string in millisecond format


I want to generate the current UTC date time in milliseconds precision but I am only be able to get it in seconds or microsec precision. Is it possible to get it in milliseconds precision?

std::cout << to_iso_extended_string(microsec_clock::universal_time()) + "Z" << std::endl;

"2020-02-27T13:05:46.543801Z"

std::cout << to_iso_extended_string(second_clock::universal_time()) + "Z" << std::endl;

"2020-02-27T13:11:00Z"

Expected format:

"2020-02-27T13:05:46.543Z"

Solution

  • I think you can take a substring from the microsecond version.

    Something like:

    std::string microsec_time = to_iso_extended_string(microsec_clock::universal_time());
    
    std::string millisec_time = microsec_time.substr(0, microsec_time.size()-3);
    
    std::cout << millisec_time << 'Z' << std::endl;
    

    It should give you the output you expect.