In this article we will discuss how to convert string to date objects in C++ using Boost Date Time Library.

Boost Date Time Library provides boost::gregorian::date type for all the calendar date related operations. But many times we encounter scenarios where we need to convert parse date from some text and then convert date in string format to Date object for further operations.

For example, we might get date in following string formats,

2016/10/30 —- YYYY/MM/DD
2016/30/10 —- YYYY/DD/MM
30-10-2016 —- DD-MM-YYYY
10 30 2016 —- MM DD YYYY

Alignment of Month, Date, year and Delimiter may vary from scenario to scenario. Let’s see simple ways to convert string to boost::gregorian::date objects using some factory functions i.e.

Delimiters

In all the above factory functions following delimiters can be – ‘,’,’-‘,’.’,’ ‘,’/’,’\0′ used to seperate months,days & Years.
For example, for these factory functions “YYYY-MM-DD” is equivalent to “YYYY/MM/DD” , “YYYY,MM.DD” & “YYYY MM DD”

Converting ISO Format String (YYYYMMDD) to Date Object

Boost provides boost::gregorian::date_from_iso_string that converts ISO Format String date to date object i.e.

Converting Simple Format (YYYY-MM-DD) String to date object

Boost provides boost::gregorian::from_simple_string that converts Simple Format String date to date object i.e.

Converting US Format (MM-DD-YYYY) String to date object

Boost provides boost::gregorian::from_us_string that converts US Format String date to date object i.e.

Converting UK Format (DD-MM-YYYY) String to date object

Boost provides boost::gregorian::from_uk_string that converts UK Format String date to date object i.e.

Instead of Month number in the string we can also use month name with all the above factory functions i.e.

Complete example is as follows,

Output:

To compile the above code use following command in linux,

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

Click Here to Subscribe for more Articles / Tutorials like this.