How can I extract the year, month, day, hour, minute, second and millisecond from an std::chrono::time_point
object?
I only saw examples on how to extract the total amount of e.g. seconds from a duration
.
How can I extract the year, month, day, hour, minute, second and millisecond from an std::chrono::time_point
object?
I only saw examples on how to extract the total amount of e.g. seconds from a duration
.
You can only extract this information from a
system_clock::time_point
. This is the only system-supplied clock that has a relationship with the civil calendar. Here is how to get the current time_point using this clock:You can then convert this to a
time_t
with:Using the C library you can then convert a
time_t
to atm
, but you must choose whether you want that conversion to happen in the UTC timezone, or you local timezone:Then you can print out the components of the tm, for example:
Additionally
If you want, you can take advantage of this non-guaranteed information:
Every implementation of
system_clock
I'm aware of is based on unix time. I.e. the number of seconds since New Years 1970 UTC, neglecting leap seconds. And the precision of this count is usually finer than seconds. Here is a complete program which extracts all of this information:It is handy to create a custom
duration
to model days:Now you can get the time since the epoch, to as fine a precision as it can manage, with:
Then truncate it to days, and subtract that off.
Then truncate it to hours, and subtract that off.
Continue until you've subtracted off the seconds.
What you're left with is the fraction of a second with the units of
system_clock::duration
. So print out that run time value and the compile time units of that value as shown.For me this program prints out:
My output indicates the
system_clock::duration
precision is microseconds. If desired, that can be truncated to milliseconds with:Update
This header-only C++11/14 library encapsulates the work above, reducing client work down to:
Which just output for me: