Home > Frameworks > boost::date_time


Dealing with time, through calculations, proper formatting, conversions between calendar types, can be a royal pain.  The rational behind the boost::date_time is it shouldn’t be harder than dealing with strings or integers.  And being portable between different platforms is a bonus too!
The Date Time framework is the first I encountered so far that require the build and linking of a library.  That is, it is not purely templated.

I got to play around with the Gregorian calendar set of classes, which I figure might be the only one I ever need.  First, you need to include the proper Gregorian header:

#include "boost/date_time/gregorian/gregorian.hpp"
using namespace boost::gregorian;
using namespace boost::posix_time;

From then on, we can define date or time objects pretty intuitively:

date someDay(2011, Jun, 12);
ptime timeOfDay(someDay, hours(10) + minutes(38) + seconds(13));

We can easily do calculations of those dates & times objects:

someDay = someDay + week(6);
timeOfDay += seconds(1);

One of the great service provided by the framework is to allow iteration loop using specific time jumps.  For instance if we want to process every hours between two dates & times, we could do like so:

ptime now = second_clock::local_time();
time_iterator iter(now, hours(1)); 
for(; iter < someDay; ++iter)
    std::cout << (*iter) << std::endl;

We can also use the Standard Library streaming system to encode or decode a date/time string into its proper representation object.  For instance:

ptime someTime;
std::stringstream encodedDateTime("2004-Jan-1 05:21:33.20");
encodedDateTime >> someTime;

There’s a lot more to the system, but I can already see it as a definitive solution for most, if not all of my Date & Time manipulation needs.


Categories: Frameworks
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: