In the C++ standard: <chrono>
C++11
Starting with C++11, the standard library contains date & time utilities, available in the <chrono>
header, with constructs within the std::chrono
namespace.
Among these you will find:
- Clocks
- Time points
- Durations
- A flexible mechanism for parsing date & time values from strings
the library is heavily templated, so that you can use a type of your choice for the raw representation (even floating-point types), and set your own resolution.
Example of use: How to get current time and date in C++?
Note that std::chrono
facilities are somewhat-compatible with the old <ctime>
header types. For example, the "system clock" class has methods for converting to and from the <ctime>
time representation, time_t
. This will be useful to you if you're combining C and C++ code, or need to expose a C interface somewhere; otherwise - try avoiding <ctime>
-based code.
C++20
The new standard version approved in 2020 added:
- Time zones
- Calendars
- More Duration types
- More time point types
- More clocks
Beyond the standard: Howard Hinnant's Date libraries
As commenters @AndyG and @doug suggest, Howard Hinnant is the "C++ date&time guy", and much of his work has actually gone into the standard - but not all of it.
Howard maintains a library/set-of-libraries of his own, named "Date".
It is based on C++11 <chrono>
, but its changes are not exactly what's been added in C++20; so especially useful if you're using C++17 or earlier. It adds:
- Timezones
- Calendars, including Julian and Islamic
- More Duration types
- More time point types
- Weeks
I'm assuming that eventually, all the good stuff from here will get standardized, but that hasn't happened yet.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…