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

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

+4
source share
2 answers

The most flexible way to do this is to convert it to struct tm, and then use it strftime(it's like sprintffor the time). Sort of:

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`

See the documentation for strftime here .

If you have localtime_sor localtime_r, you should use either preference localtime.

, , , . "" .

+3

, , , - , API C, , . .

. - :

#include "date.h"
#include <iostream>

int
main()
{
    using namespace date;
    std::cout << std::chrono::system_clock::now() << '\n';
}

:

2017-09-15 13:11:34.356648

using namespace date;, system_clock::time_point ( namespace std::chrono). : system_clock::time_point (microseconds, macOS).

strftime - , , . , :

#include "date.h"
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    std::cout << format("%D %T %Z\n", floor<milliseconds>(system_clock::now()));
}

:

09/15/17 13:17:40.466 UTC
+4

Source: https://habr.com/ru/post/1624798/


All Articles