Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++11

chrono

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

like image 653
Seihyung Oh Avatar asked Jan 18 '16 14:01

Seihyung Oh


People also ask

What is std :: Chrono :: Time_point?

Class template std::chrono::time_point represents a point in time. It is implemented as if it stores a value of type Duration indicating the time interval from the start of the Clock 's epoch. Clock must meet the requirements for Clock or be std::chrono::local_t (since C++20).

What does std :: Chrono :: System_clock :: now return?

std::chrono::system_clock::now Returns a time point representing with the current point in time.


1 Answers

Howard Hinnant's free, open source, header-only, portable date/time library is a modern way to do this that doesn't traffic through the old C API, and doesn't require that you discard all of your sub-second information. This library is also being proposed for standardization.

There is a lot of flexibility in formatting. The easiest way is to just stream out:

#include "date.h" #include <iostream>  int main() {     using namespace date;     std::cout << std::chrono::system_clock::now() << '\n'; } 

This just output for me:

2017-09-15 13:11:34.356648 

The using namespace date; is required in order to find the streaming operator for the system_clock::time_point (it isn't legal for my lib to insert it into namespace std::chrono). No information is lost in this format: the full precision of your system_clock::time_point will be output (microseconds where I ran this on macOS).

The full suite of strftime-like formatting flags is available for other formats, with minor extensions to handle things like fractional seconds. Here is another example that outputs with millisecond precision:

#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())); } 

which just output for me:

09/15/17 13:17:40.466 UTC 
like image 96
Howard Hinnant Avatar answered Sep 18 '22 14:09

Howard Hinnant