How to convert std::chrono::time_point to string

后端 未结 3 1569
闹比i
闹比i 2020-12-09 16:32

How to convert std::chrono::time_point to string? For example: \"201601161125\".

3条回答
  •  离开以前
    2020-12-09 16:57

    The most flexible way to do so is to convert it to struct tm and then use strftime (it's like sprintf for time). Something like:

    std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
    std::time_t now_c = std::chrono::system_clock::to_time_t(now);
    std::tm now_tm = *std::localtime(&now_c);
    /// now you can format the string as you like with `strftime`
    

    Look up the documentation for strftime here.

    If you have localtime_s or localtime_r available you should use either in preference to localtime.

    There are many other ways to do this, but, while mostly easier to use, these result in some predefined string representation. You could just "hide" all of the above in a function for ease of use.

提交回复
热议问题