How to convert std::chrono::time_point to calendar datetime string with fractional seconds?

后端 未结 7 2067
生来不讨喜
生来不讨喜 2020-11-27 02:50

How to convert std::chrono::time_point to calendar datetime string with fractional seconds?

For example:

\"10-10-2012 12:38:40.123456\"         


        
7条回答
  •  执笔经年
    2020-11-27 03:15

    In general, you can't do this in any straightforward fashion. time_point is essentially just a duration from a clock-specific epoch.

    If you have a std::chrono::system_clock::time_point, then you can use std::chrono::system_clock::to_time_t to convert the time_point to a time_t, and then use the normal C functions such as ctime or strftime to format it.


    Example code:

    std::chrono::system_clock::time_point tp = std::chrono::system_clock::now();
    std::time_t time = std::chrono::system_clock::to_time_t(tp);
    std::tm timetm = *std::localtime(&time);
    std::cout << "output : " << std::put_time(&timetm, "%c %Z") << "+"
              << std::chrono::duration_cast(tp.time_since_epoch()).count() % 1000 << std::endl;
    

提交回复
热议问题