How to convert std::chrono::time_point
to string?
For example: "201601161125"
.
C++ – How to Convert std::chrono::time_point to String
c++-chronoc++11
Related Solutions
It's very unfortunate that you see dynamic allocation so often. That just shows how many bad C++ programmers there are.
In a sense, you have two questions bundled up into one. The first is when should we use dynamic allocation (using new
)? The second is when should we use pointers?
The important take-home message is that you should always use the appropriate tool for the job. In almost all situations, there is something more appropriate and safer than performing manual dynamic allocation and/or using raw pointers.
Dynamic allocation
In your question, you've demonstrated two ways of creating an object. The main difference is the storage duration of the object. When doing Object myObject;
within a block, the object is created with automatic storage duration, which means it will be destroyed automatically when it goes out of scope. When you do new Object()
, the object has dynamic storage duration, which means it stays alive until you explicitly delete
it. You should only use dynamic storage duration when you need it.
That is, you should always prefer creating objects with automatic storage duration when you can.
The main two situations in which you might require dynamic allocation:
- You need the object to outlive the current scope - that specific object at that specific memory location, not a copy of it. If you're okay with copying/moving the object (most of the time you should be), you should prefer an automatic object.
- You need to allocate a lot of memory, which may easily fill up the stack. It would be nice if we didn't have to concern ourselves with this (most of the time you shouldn't have to), as it's really outside the purview of C++, but unfortunately, we have to deal with the reality of the systems we're developing for.
When you do absolutely require dynamic allocation, you should encapsulate it in a smart pointer or some other type that performs RAII (like the standard containers). Smart pointers provide ownership semantics of dynamically allocated objects. Take a look at std::unique_ptr
and std::shared_ptr
, for example. If you use them appropriately, you can almost entirely avoid performing your own memory management (see the Rule of Zero).
Pointers
However, there are other more general uses for raw pointers beyond dynamic allocation, but most have alternatives that you should prefer. As before, always prefer the alternatives unless you really need pointers.
You need reference semantics. Sometimes you want to pass an object using a pointer (regardless of how it was allocated) because you want the function to which you're passing it to have access that that specific object (not a copy of it). However, in most situations, you should prefer reference types to pointers, because this is specifically what they're designed for. Note this is not necessarily about extending the lifetime of the object beyond the current scope, as in situation 1 above. As before, if you're okay with passing a copy of the object, you don't need reference semantics.
You need polymorphism. You can only call functions polymorphically (that is, according to the dynamic type of an object) through a pointer or reference to the object. If that's the behavior you need, then you need to use pointers or references. Again, references should be preferred.
You want to represent that an object is optional by allowing a
nullptr
to be passed when the object is being omitted. If it's an argument, you should prefer to use default arguments or function overloads. Otherwise, you should preferably use a type that encapsulates this behavior, such asstd::optional
(introduced in C++17 - with earlier C++ standards, useboost::optional
).You want to decouple compilation units to improve compilation time. The useful property of a pointer is that you only require a forward declaration of the pointed-to type (to actually use the object, you'll need a definition). This allows you to decouple parts of your compilation process, which may significantly improve compilation time. See the Pimpl idiom.
You need to interface with a C library or a C-style library. At this point, you're forced to use raw pointers. The best thing you can do is make sure you only let your raw pointers loose at the last possible moment. You can get a raw pointer from a smart pointer, for example, by using its
get
member function. If a library performs some allocation for you which it expects you to deallocate via a handle, you can often wrap the handle up in a smart pointer with a custom deleter that will deallocate the object appropriately.
(In this post I will omit std::chrono::
qualifications for clarity. I trust you know where they go.)
The reason your code example fails to compile is that there is a mismatch between the return type of system_clock::now()
and the type of variable you are trying to assign this to (time_point<system_clock, nanoseconds>
).
The documented return value of system_clock::now()
is system_clock::time_point
, which is a typedef for time_point<system_clock, system_clock::duration>
. system_clock::duration
is implementation-defined, with microseconds
and nanoseconds
being commonly used. It seems that your implementation uses microseconds
, so the return type of system_clock::now()
is time_point<system_clock, microseconds>
.
time_point
s with different durations are not implicitly convertible to one another, so you get a compiler error.
You can explicitly convert time points with different durations using time_point_cast
, so the following would compile on your system:
time_point<system_clock, nanoseconds> time_point;
time_point = time_point_cast<nanoseconds>(system_clock::now());
Notice the explicit template parameter to time_point_cast
is the target duration type, not the target time_point type. The clock types must match in a time_point_cast
, so specifying the entire time_point type (which is templated on both the clock type and the duration type) would be redundant.
Of course in your case, since you are just looking to print the time point, there is no need for it to be at any specific resolution, so you can just declare time_point
to be the same type as what system_clock::now()
returns to begin with. A simple way to do that is to use the system_clock::time_point
typedef:
system_clock::time_point time_point;
time_point = system_clock::now(); // no time_point_cast needed
Since this is C++11, you can also just use auto
:
auto time_point = system_clock::now();
Having solved this compiler error, the conversion to time_t
works just fine:
std::time_t now_c = std::chrono::system_clock::to_time_t(time_point);
and you can now use standard methods for displaying time_t
values, like std::ctime
or std::strftime
. (As Cassio Neri points out in a comment to your question, the more C++-y std::put_time
function is not yet supported by GCC).
Best Answer
Update for C++20:
This can now easily be done in C++20:
Output:
Demo.
Original Answer:
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:
This just output for me:
The
using namespace date;
is required in order to find the streaming operator for thesystem_clock::time_point
(it isn't legal for my lib to insert it intonamespace std::chrono
). No information is lost in this format: the full precision of yoursystem_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:which just output for me: