The C++ Boost date_time library wraps the vagaries of time, date, and high resolution timing into a single header file, #include <boost/date_time.hpp>
. With all it does, it is relatively easy to use, and far easier than integrating your particular OS's date functions + low-resolution time function + high resolution time function, then accounting for time zones... The most difficult things about using the library are understanding how various time/date concepts are embodied in classes and the multiple-level namespaces.
Concept | Class | Example |
Time Duration | boost::posix_time::time_duration |
3hr 40min 11s |
Date | boost::gregorian::date |
May 5, 2012 |
Absolute Time | boost::posix_time |
May 5, 2012 23:53 UTC |
Time Period | boost::posix_time::time_period |
May 5, 2012 02:00 UTC thru May 12, 2012 18:00 UTC |
Example C++ code demonstrating the different classes listed in the table above are show below. In each case, the first use of a function or member data is fully namespace qualified. I do this because I get frustrated with examples that presume the reader knows the namespace to use. To avoid visual clutter and verbosity, after the first use we take advantage of using namespace
.
[crayon title="Example use of boost::posix_time::time_duration" url="2012/05/timeDurationExample.hpp" lang="cpp"/]
[crayon title="Example use of boost::gregorian::date" url="2012/05/dateExample.hpp" lang="cpp"/]
[crayon title="Example use of boost::posix_time::ptime" url="2012/05/ptimeExample.hpp" lang="cpp"/]
[crayon title="Example use of boost::posix_time::ptime" url="2012/05/timePeriodExample.hpp" lang="cpp"/]
This post supplements two videos on the subject. The source file developed in the video is available below, as is the re-usable class Elapsed.hpp
.
[youtube=http://www.youtube.com/watch?v=fxhOdIAKYhc]
[youtube=http://www.youtube.com/watch?v=wH2Fd_cchsM]
[crayon title="File date_time.cpp developed in the video" url="2012/05/date_time.cpp" lang="cpp"/]
[crayon title="Reusable class Elapsed.hpp developed in the video" url="2012/05/Elapsed.hpp" lang="cpp"/]