In this article we will discuss how to calculate difference between two dates and how to iterate over a date range using C++ Boost Date Time Library.

date_duration

Boost Date Time Library provides a duration type to represent the duration between two dates i.e.

With this date_duration object we can get the duration between 2 dates in days i.e.

We can also add and subtract this date_duration object from a date object. For example, let’s add 3 week duration in a date object i.e.

Complete Example is as follows,

Output:

Date Period

Boost Date Time Library provides a type boost::gregorian::date_period to represents a period between two Dates i.e.

We can fetch days, months and years in this date period and can also iterate over it.

Fetching date_duration object from date_period,

Iterate over the Date Period

date_period provides month, week and day iterators to iterate over a date period.┬áLet’s see a a monthly iterator to iterate between 2 dates i.e.

Similarly date_period provides week and day iterators to iterate over a date period i.e.

boost::gregorian::week_iterator
boost::gregorian::day_iterator

Complete Example is as follows,

Output:

Let’s see a practical example of day_iterator of date_period i.e.

Iterate Over last 20 Years and print how many times 1st Jan was on Sunday

Output:

To compile the above examples in Linux, use following command,

g++ –std=c++11 example.cpp -lboost_date_time

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,