Boost C++ Libraries

“...one of the most highly regarded and expertly designed C++ library projects in the world.” Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

PrevUpHomeNext

Examples

General Usage Examples

The following provides some sample usage of dates. See Date Programming for more details.

    
	 using namespace boost::gregorian; 
	 date weekstart(2002,Feb,1);
	 date weekend  = weekstart + week(1);
	 date d2 = d1 + days(5);
	 date today = day_clock::local_day();
	 if (d2 >= today) {} //date comparison operators
	 
	 date_period thisWeek(d1,d2);
	 if (thisWeek.contains(today)) {}//do something
	
	 //iterate and print the week
	 day_iterator itr(weekstart);
	 while (itr <= weekend) {
	   std::cout << (*itr) << std::endl;
           ++itr;
	 }  
         //input streaming
         std::stringstream ss("2004-Jan-1");
         ss >> d3;
        
         //localized i/o using facets
         std::locale global;
         std::locale german(global, 
                            new date_facet(de_short_month_names, 
                                           de_long_month_names,
                                           de_special_value_names,
                                           de_long_weekday_names,
                                           de_long_weekday_names,
                                           '.', 
                                           boost::date_time::ymd_order_dmy));
         std::cout.imbue(global2); 
         date d4(2002, Oct, 1);
         std::cout << d4; //01.Okt.2002

         //date generator functions
         date d5 = next_weekday(d4, Sunday); //calculate sunday following d4

         //define a shorthand for the nth_day_of_the_week_in_month function object
	 typedef nth_day_of_the_week_in_month nth_dow;
         //US labor day is first Monday in Sept
	 nth_dow labor_day(nth_dow::first,Monday, Sep); 
	 date d6 = labor_day.get_date(2004); //calculate a specific date from functor
    

The following provides some example code using times. See Time Programming for more details.

    
	 use namespace boost::posix_time; 
	 date d(2002,Feb,1); //an arbitrary date
	 ptime t1(d, hours(5)+nanosec(100)); //date + time of day offset
	 ptime t2 = t1 - minutes(4)+seconds(2);
	 ptime now = second_clock::local_time(); //use the clock
	 date today = now.date(); //Get the date part out of the time
	 date tommorrow = today + date_duration(1);
	 ptime tommorrow_start(tommorrow); //midnight 

         //input streaming
         std::stringstream ss("2004-Jan-1 05:21:33.20");
         ss >> t2;

	 //starting at current time iterator adds by one hour
	 time_iterator titr(now,hours(1)); 
	 for (; titr < tommorrow_start; ++titr) {
	   std::cout << (*titr) << std::endl;
	 }

    
top

Dates as Strings

Various parsing and output of strings.

    

      /* The following is a simple example that shows conversion of dates 
       * to and from a std::string.
       * 
       * Expected output:
       * 2001-Oct-09
       * 2001-10-09
       * Tuesday October 9, 2001
       * An expected exception is next: 
       * Exception: Month number is out of range 1..12
       */

      #include "boost/date_time/gregorian/gregorian.hpp"
      #include <iostream>
      #include <string>

      int
      main() 
      {

	using namespace boost::gregorian;

	try {
	  // The following date is in ISO 8601 extended format (CCYY-MM-DD)
	  std::string s("2001-10-9"); //2001-October-09
	  date d(from_simple_string(s));
	  std::cout << to_simple_string(d) << std::endl;
	  
	  //Read ISO Standard(CCYYMMDD) and output ISO Extended
	  std::string ud("20011009"); //2001-Oct-09
	  date d1(from_undelimited_string(ud));
	  std::cout << to_iso_extended_string(d1) << std::endl;
	  
	  //Output the parts of the date - Tuesday October 9, 2001
	  date::ymd_type ymd = d1.year_month_day();
	  greg_weekday wd = d1.day_of_week();
	  std::cout << wd.as_long_string() << " "
		    << ymd.month.as_long_string() << " "
		    << ymd.day << ", " << ymd.year
		    << std::endl;

	  //Let's send in month 25 by accident and create an exception
	  std::string bad_date("20012509"); //2001-??-09
	  std::cout << "An expected exception is next: " << std::endl;
	  date wont_construct(from_undelimited_string(bad_date));
	  //use wont_construct so compiler doesn't complain, but you wont get here!
	  std::cout << "oh oh, you shouldn't reach this line: " 
		    << to_iso_string(wont_construct) << std::endl;
	}
	catch(std::exception& e) {
	  std::cout << "  Exception: " <<  e.what() << std::endl;
	}


	return 0;
      }

    
  

top

Days Alive

Calculate the number of days you have been living using durations and dates.

    
      /* Short example that calculates the number of days since user was born.
       * Demonstrates comparisons of durations, use of the day_clock,
       * and parsing a date from a string.
       */

      #include "boost/date_time/gregorian/gregorian.hpp"
      #include <iostream>

      int
      main() 
      {
	
	using namespace boost::gregorian;
	std::string s;
	std::cout << "Enter birth day YYYY-MM-DD (eg: 2002-02-01): ";
	std::cin >> s;
	try {
	  date birthday(from_simple_string(s));
	  date today = day_clock::local_day();
	  days days_alive = today - birthday;
	  days one_day(1);
	  if (days_alive == one_day) {
	    std::cout << "Born yesterday, very funny" << std::endl;
	  }
	  else if (days_alive < days(0)) {
	    std::cout << "Not born yet, hmm: " << days_alive.days() 
		      << " days" <<std::endl;
	  }
	  else {
	    std::cout << "Days alive: " << days_alive.days() << std::endl;
	  }

	}
	catch(...) {
	  std::cout << "Bad date entered: " << s << std::endl;
	}
	return 0;
      }
    
  

top

Days Between New Years

Calculate the number of days till new years

    
      /* Provides a simple example of using a date_generator, and simple
       * mathematical operatorations, to calculate the days since 
       * New Years day of this year, and days until next New Years day.
       *
       * Expected results:
       * Adding together both durations will produce 366 (365 in a leap year).
       */
      #include <iostream>
      #include "boost/date_time/gregorian/gregorian.hpp"

      int
      main() 
      {
	
	using namespace boost::gregorian;

	date today = day_clock::local_day();
	partial_date new_years_day(1,Jan);
	//Subtract two dates to get a duration
	days days_since_year_start = today - new_years_day.get_date(today.year());
	std::cout << "Days since Jan 1: " << days_since_year_start.days() 
		  << std::endl;
	
	days days_until_year_start = new_years_day.get_date(today.year()+1) - today;
	std::cout << "Days until next Jan 1: " << days_until_year_start.days() 
		  << std::endl;
	return 0;
      };

    
  

top

End of the Months

Iterates accross the remaining months in a given year, always landing on the last day of the month.

    
      /* Simple program that uses the gregorian calendar to find the last
       * day of the month and then display the last day of every month left 
       * in the year.
       */

      #include "boost/date_time/gregorian/gregorian.hpp"
      #include <iostream>

      int
      main()
      {
	using namespace boost::gregorian;
	
	std::cout << "   Enter Year(ex: 2002): ";
	int year, month;
	std::cin >> year;
	std::cout << "   Enter Month(1..12): ";
	std::cin >> month;
	try {
	  int day = gregorian_calendar::end_of_month_day(year,month);
	  date end_of_month(year,month,day);

	  //Iterate thru by months --
	  month_iterator mitr(end_of_month,1);
	  date start_of_next_year(year+1, Jan, 1);
	  //loop thru the days and print each one
	  while (mitr < start_of_next_year){
	    std::cout << to_simple_string(*mitr) << std::endl;
	    ++mitr;
	  }

	}
	catch(...) {
	  std::cout << "Invalid Date Entered" << std::endl;
	}
	return 0;

      }

    
  

top

Localization Demonstration

The boost::date_time library provides the ability to create customized locale facets. Date ordering, language, seperators, and abbreviations can be customized.

    

      /* The following shows the creation of a facet for the output of 
       * dates in German (please forgive me for any errors in my German --
       * I'm not a native speaker).
       */

      #include "boost/date_time/gregorian/gregorian.hpp"
      #include <iostream>

      /* Define a series of char arrays for short and long name strings to be 
       * associated with date output. */
      const char* const de_short_month_names[] = 
      {
	"Jan", "Feb", "Mar", "Apr", "Mai", "Jun",
	"Jul", "Aug", "Sep", "Okt", "Nov", "Dez", "NAM" 
      };
      const char* const de_long_month_names[] =
      {
	"Januar", "Februar", "Marz", "April", "Mai",
	"Juni", "Juli", "August", "September", "Oktober",
	"November", "Dezember", "NichtDerMonat"
      };
      const char* const de_special_value_names[] =
      {
	"NichtDatumzeit", "-unbegrenztheit", "+unbegrenztheit"
      };
      const char* const de_long_weekday_names[] = 
      {
	"Sonntag", "Montag", "Dienstag", "Mittwoch",
	"Donnerstag", "Freitag", "Samstag"
      };
      const char* const de_short_weekday_names[] =
      {
	"Son", "Mon", "Die","Mit", "Don", "Fre", "Sam"
      };

      const char* const us_short_month_names[] = 
      {
	"Jan", "Feb", "Mar", "Apr", "May", "Jun",
	"Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "NAD"
      };
      const char* const us_long_month_names[] =
      {
	"January", "February", "March", "April", "May",
	"June", "July", "August", "September", "October",
	"November", "December", "Not-A-Date"
      };
      const char* const us_special_value_names[] =
      { 
	"Not-A-Date", "-infinity", "+infinity"
      };
      const char* const us_long_weekday_names[] =
      {
	"Sunday", "Monday", "Tuesday", "Wenesday", 
	"Thursday", "Friday", "Saturday"
      };
      const char* const us_short_weekday_names[] =
      {
	"Sun", "Mon", "Tue","Wed", "Thu", "Fri", "Sat"
      };


      int
      main() 
      {

      #ifndef BOOST_DATE_TIME_NO_LOCALE

	using namespace boost::gregorian;
	typedef boost::date_time::all_date_names_put<greg_facet_config> date_facet;
	
	//create a new local
	std::locale default_locale;
	std::locale german_dates1(default_locale, 
				  new date_facet(de_short_month_names, 
						 de_long_month_names,
						 de_special_value_names,
						 de_short_weekday_names,
						 de_long_weekday_names,
						 '.',
						 boost::date_time::ymd_order_dmy,
						 boost::date_time::month_as_integer));
	
	date d1(2002, Oct, 1);
	std::cout.imbue(german_dates1); 
	// output the date in German using short month names
	std::cout << d1 << std::endl; //01.10.2002
	
	std::locale german_dates2(default_locale, 
				  new date_facet(de_short_month_names, 
						 de_long_month_names,
						 de_special_value_names,
						 de_short_weekday_names,
						 de_long_weekday_names,
						 '.',
						 boost::date_time::ymd_order_dmy,
						 boost::date_time::month_as_long_string));
	
	std::cout.imbue(german_dates2); 
	greg_month m = d1.month();
	std::cout << m << std::endl; //Oktober
	
	greg_weekday wd = d1.day_of_week();
	std::cout << wd << std::endl; //Dienstag


	//Numeric date format with US month/day/year ordering
	std::locale usa_dates1(default_locale, 
			       new date_facet(us_short_month_names, 
					      us_long_month_names,
					      us_special_value_names,
					      us_short_weekday_names,
					      us_long_weekday_names,
					      '/',
					      boost::date_time::ymd_order_us,
					      boost::date_time::month_as_integer));
	
	std::cout.imbue(usa_dates1); 
	std::cout << d1 << std::endl; //  10/01/2002
	//English names, iso order (year-month-day), '-' separator
	std::locale usa_dates2(default_locale, 
			       new date_facet(us_short_month_names, 
					      us_long_month_names,
					      us_special_value_names,
					      us_short_weekday_names,
					      us_long_weekday_names,
					      '-',
					      boost::date_time::ymd_order_iso,
					      boost::date_time::month_as_short_string));

	std::cout.imbue(usa_dates2); 
	std::cout << d1 << std::endl; //  2002-Oct-01
	
	
      #else 
	std::cout << "Sorry, localization is not supported by this compiler/library" 
		  << std::endl;
      #endif
	return 0;

      }
    
  

top

Date Period Calculations

Calculates if a date is in an 'irregular' collection of periods using period calculation functions.

    
      /*
      This example demonstrates a simple use of periods for the calculation
      of date information.

      The example calculates if a given date is a weekend or holiday
      given an exclusion set.  That is, each weekend or holiday is
      entered into the set as a time interval.  Then if a given date
      is contained within any of the intervals it is considered to
      be within the exclusion set and hence is a offtime.

      Output:
      Number Excluded Periods: 5
      20020202/20020203
      20020209/20020210
      20020212/20020212
      20020216/20020217
      In Exclusion Period: 20020216 --> 20020216/20020217
      20020223/20020224

      */


      #include "boost/date_time/gregorian/gregorian.hpp"
      #include <set>
      #include <algorithm>
      #include <iostream>

      typedef std::set<boost::gregorian::date_period> date_period_set;

      //Simple population of the exclusion set
      date_period_set
      generateExclusion()
      {
	using namespace boost::gregorian;
	date_period periods_array[] = 
	  { date_period(date(2002,Feb,2), date(2002,Feb,4)),//weekend of 2nd-3rd
	    date_period(date(2002,Feb,9), date(2002,Feb,11)),
	    date_period(date(2002,Feb,16), date(2002,Feb,18)),
	    date_period(date(2002,Feb,23), date(2002,Feb,25)),
	    date_period(date(2002,Feb,12), date(2002,Feb,13))//a random holiday 2-12
	  };
	const int num_periods = sizeof(periods_array)/sizeof(date_period);

	date_period_set ps;
	//insert the periods in the set
	std::insert_iterator<date_period_set> itr(ps, ps.begin());
	std::copy(periods_array, periods_array+num_periods, itr );
	return ps;
	
      }


      int main() 
      {
	using namespace boost::gregorian;
	
	date_period_set ps = generateExclusion();
	std::cout << "Number Excluded Periods: "  << ps.size() << std::endl;

	date d(2002,Feb,16);
	date_period_set::const_iterator i = ps.begin();
	//print the periods, check for containment
	for (;i != ps.end(); i++) {
	  std::cout << to_iso_string(*i) << std::endl;
	  //if date is in exclusion period then print it
	  if (i->contains(d)) {
	    std::cout << "In Exclusion Period: "
		<< to_iso_string(d) << " --> " << to_iso_string(*i)
		<< std::endl;
	  }
	}

	return 0;  

      }

    
  

top

Print Holidays

This is an example of using functors to define a holiday schedule

    

      /* Generate a set of dates using a collection of date generators
       * Output looks like:
       * Enter Year: 2002
       * 2002-Jan-01 [Tue]
       * 2002-Jan-21 [Mon]
       * 2002-Feb-12 [Tue]
       * 2002-Jul-04 [Thu]
       * 2002-Sep-02 [Mon]
       * 2002-Nov-28 [Thu]
       * 2002-Dec-25 [Wed]
       * Number Holidays: 7
       */

      #include "boost/date_time/gregorian/gregorian.hpp"
      #include <algorithm>
      #include <functional>
      #include <vector>
      #include <iostream>
      #include <set>

      void
      print_date(boost::gregorian::date d) 
      {
	using namespace boost::gregorian;
      #if defined(BOOST_DATE_TIME_NO_LOCALE)
	std::cout << to_simple_string(d) << " [" << d.day_of_week() << "]\n";
      #else
	std::cout << d << " [" << d.day_of_week() << "]\n";
      #endif
      }


      int
      main() {

	std::cout << "Enter Year: ";
	int year;
	std::cin >> year;

	using namespace boost::gregorian;

	//define a collection of holidays fixed by month and day
	std::vector<year_based_generator*> holidays;
	holidays.push_back(new partial_date(1,Jan)); //Western New Year
	holidays.push_back(new partial_date(4,Jul)); //US Independence Day
	holidays.push_back(new partial_date(25, Dec));//Christmas day


	//define a shorthand for the nth_day_of_the_week_in_month function object
	typedef nth_day_of_the_week_in_month nth_dow;
	
	//US labor day
	holidays.push_back(new nth_dow(nth_dow::first,  Monday,   Sep)); 
	//MLK Day
	holidays.push_back(new nth_dow(nth_dow::third,  Monday,   Jan)); 
	//Pres day
	holidays.push_back(new nth_dow(nth_dow::second, Tuesday,  Feb)); 
	//Thanksgiving
	holidays.push_back(new nth_dow(nth_dow::fourth, Thursday, Nov)); 

	typedef std::set<date> date_set;
	date_set all_holidays;
	
	for(std::vector<year_based_generator*>::iterator it = holidays.begin();
	    it != holidays.end(); ++it)
	{
	  all_holidays.insert((*it)->get_date(year));
	}

	//print the holidays to the screen
	std::for_each(all_holidays.begin(), all_holidays.end(), print_date);
	std::cout << "Number Holidays: " << all_holidays.size() << std::endl;

	return 0;
      }

    
  

top

Print Month

Simple utility to print out days of the month with the days of a month. Demontstrates date iteration (date_time::date_itr).

    
      /* This example prints all the dates in a month. It demonstrates
       * the use of iterators as well as functions of the gregorian_calendar
       * 
       * Output:
       * Enter Year: 2002
       * Enter Month(1..12): 2
       * 2002-Feb-01 [Fri]
       * 2002-Feb-02 [Sat]
       * 2002-Feb-03 [Sun]
       * 2002-Feb-04 [Mon]
       * 2002-Feb-05 [Tue]
       * 2002-Feb-06 [Wed]
       * 2002-Feb-07 [Thu]
       */

      #include "boost/date_time/gregorian/gregorian.hpp"
      #include <iostream>

      int
      main()
      {
	std::cout << "Enter Year: ";
	int year, month;
	std::cin >> year;
	std::cout << "Enter Month(1..12): ";
	std::cin >> month;

	using namespace boost::gregorian;
	try {
	  //Use the calendar to get the last day of the month
	  int eom_day = gregorian_calendar::end_of_month_day(year,month);
	  date endOfMonth(year,month,eom_day);

	  //construct an iterator starting with firt day of the month
	  day_iterator ditr(date(year,month,1));
	  //loop thru the days and print each one
	  for (; ditr <= endOfMonth; ++ditr) {
      #if defined(BOOST_DATE_TIME_NO_LOCALE) 
	    std::cout << to_simple_string(*ditr) << " ["
      #else
	    std::cout << *ditr << " ["
      #endif
		      << ditr->day_of_week() << "]"
		      << std::endl; 
	  }
	}
	catch(std::exception& e) {

	  std::cout << "Error bad date, check your entry: \n"
		    << "  Details: " << e.what() << std::endl;
	}
	return 0;
      }

    
  

top

Month Adding

Adding a month to a day without the use of iterators.

    
      /* Simple program that uses the gregorian calendar to progress by exactly
       * one month, irregardless of how many days are in that month.
       *
       * This method can be used as an alternative to iterators
       */

      #include "boost/date_time/gregorian/gregorian.hpp"
      #include <iostream>

      int
      main()
      {

	using namespace boost::gregorian;
	typedef boost::date_time::month_functor<date> add_month;

	date d = day_clock::local_day();
	add_month mf(1);
	date d2 = d + mf.get_offset(d);
	std::cout << "Today is: " << to_simple_string(d) << ".\n"
	  << "One month from today will be: " << to_simple_string(d2) 
	  << std::endl;

	return 0;
      }
    
  

top

Time Math

Various types of calculations with times and time durations.

    
      /* Some simple examples of constructing and calculating with times
       * Output:
       * 2002-Feb-01 00:00:00 - 2002-Feb-01 05:04:02.001000000 = -5:04:02.001000000
       */

      #include "boost/date_time/posix_time/posix_time.hpp"
      #include <iostream>

      int
      main() 
      {
	using namespace boost::posix_time;
	using namespace boost::gregorian;

	date d(2002,Feb,1); //an arbitrary date
	//construct a time by adding up some durations durations
	ptime t1(d, hours(5)+minutes(4)+seconds(2)+millisec(1));
	//construct a new time by subtracting some times
	ptime t2 = t1 - hours(5)- minutes(4)- seconds(2)- millisec(1);
	//construct a duration by taking the difference between times
	time_duration td = t2 - t1;
	  
	std::cout << to_simple_string(t2) << " - " 
		  << to_simple_string(t1) << " = "
		  << to_simple_string(td) << std::endl;
	
	return 0;
      }
    
  

top

Print Hours

Demonstrate time iteration, clock retrieval, and simple calculation.

    
      /* Print the remaining hours of the day
       * Uses the clock to get the local time 
       * Use an iterator to iterate over the remaining hours
       * Retrieve the date part from a time
       *
       * Expected Output something like:
       *
       * 2002-Mar-08 16:30:59
       * 2002-Mar-08 17:30:59
       * 2002-Mar-08 18:30:59
       * 2002-Mar-08 19:30:59
       * 2002-Mar-08 20:30:59
       * 2002-Mar-08 21:30:59
       * 2002-Mar-08 22:30:59
       * 2002-Mar-08 23:30:59
       * Time left till midnight: 07:29:01
       */

      #include "boost/date_time/posix_time/posix_time.hpp"
      #include <iostream>

      int
      main() 
      {
	using namespace boost::posix_time;
	using namespace boost::gregorian;

	//get the current time from the clock -- one second resolution
	ptime now = second_clock::local_time();
	//Get the date part out of the time
	date today = now.date();
	date tommorrow = today + days(1);
	ptime tommorrow_start(tommorrow); //midnight 

	//iterator adds by one hour
	time_iterator titr(now,hours(1)); 
	for (; titr < tommorrow_start; ++titr) {
	  std::cout << to_simple_string(*titr) << std::endl;
	}
	
	time_duration remaining = tommorrow_start - now;
	std::cout << "Time left till midnight: " 
		  << to_simple_string(remaining) << std::endl;
	return 0;
      }

    
  

top

Local to UTC Conversion

Demonstrate utc to local and local to utc calculations including dst.

    

      /* Demonstrate conversions between a local time and utc
       * Output:
       * 
       * UTC <--> New York while DST is NOT active (5 hours)
       * 2001-Dec-31 19:00:00 in New York is 2002-Jan-01 00:00:00 UTC time 
       * 2002-Jan-01 00:00:00 UTC is 2001-Dec-31 19:00:00 New York time 
       * 
       * UTC <--> New York while DST is active (4 hours)
       * 2002-May-31 20:00:00 in New York is 2002-Jun-01 00:00:00 UTC time 
       * 2002-Jun-01 00:00:00 UTC is 2002-May-31 20:00:00 New York time 
       * 
       * UTC <--> Arizona (7 hours)
       * 2002-May-31 17:00:00 in Arizona is 2002-Jun-01 00:00:00 UTC time 
       */

      #include "boost/date_time/posix_time/posix_time.hpp"
      #include "boost/date_time/local_time_adjustor.hpp"
      #include "boost/date_time/c_local_time_adjustor.hpp"
      #include <iostream>

      int
      main() 
      {
	using namespace boost::posix_time;
	using namespace boost::gregorian;

	//This local adjustor depends on the machine TZ settings-- highly dangerous!
	typedef boost::date_time::c_local_adjustor<ptime> local_adj;
	ptime t10(date(2002,Jan,1), hours(7)); 
	ptime t11 = local_adj::utc_to_local(t10);
	std::cout << "UTC <--> Zone base on TZ setting" << std::endl;
	std::cout << to_simple_string(t11) << " in your TZ is " 
		  << to_simple_string(t10) << " UTC time "
		  << std::endl;
	time_duration td = t11 - t10;
	std::cout << "A difference of: " 
		  << to_simple_string(td) << std::endl;


	//eastern timezone is utc-5
	typedef boost::date_time::local_adjustor<ptime, -5, us_dst> us_eastern;

	ptime t1(date(2001,Dec,31), hours(19)); //5 hours b/f midnight NY time

	std::cout << "\nUTC <--> New York while DST is NOT active (5 hours)" 
		  << std::endl;
	ptime t2 =  us_eastern::local_to_utc(t1);
	std::cout << to_simple_string(t1) << " in New York is " 
		  << to_simple_string(t2) << " UTC time "
		  << std::endl;

	ptime t3 = us_eastern::utc_to_local(t2);//back should be the same
	std::cout << to_simple_string(t2) << " UTC is " 
		  << to_simple_string(t3) << " New York time "
		  << "\n\n";

	ptime t4(date(2002,May,31), hours(20)); //4 hours b/f midnight NY time
	std::cout << "UTC <--> New York while DST is active (4 hours)" << std::endl;
	ptime t5 = us_eastern::local_to_utc(t4);
	std::cout << to_simple_string(t4) << " in New York is " 
		  << to_simple_string(t5) << " UTC time "
		  << std::endl;

	ptime t6 = us_eastern::utc_to_local(t5);//back should be the same
	std::cout << to_simple_string(t5) << " UTC is " 
		  << to_simple_string(t6) << " New York time "
		  << "\n" << std::endl;

	  
	//Arizona timezone is utc-7 with no dst
	typedef boost::date_time::local_adjustor<ptime, -7, no_dst> us_arizona;

	ptime t7(date(2002,May,31), hours(17)); 
	std::cout << "UTC <--> Arizona (7 hours)" << std::endl;
	ptime t8 = us_arizona::local_to_utc(t7);
	std::cout << to_simple_string(t7) << " in Arizona is " 
		  << to_simple_string(t8) << " UTC time "
		  << std::endl;

	return 0;
      }

    
  

top

Time Periods

Demonstrate some simple uses of time periods.

    

      /* Some simple examples of constructing and calculating with times
       * Returns:
       * [2002-Feb-01 00:00:00/2002-Feb-01 23:59:59.999999999] contains 2002-Feb-01 03:00:05
       * [2002-Feb-01 00:00:00/2002-Feb-01 23:59:59.999999999] intersected with
       * [2002-Feb-01 00:00:00/2002-Feb-01 03:00:04.999999999] is 
       * [2002-Feb-01 00:00:00/2002-Feb-01 03:00:04.999999999]
       */

      #include "boost/date_time/posix_time/posix_time.hpp"
      #include <iostream>

      using namespace boost::posix_time;
      using namespace boost::gregorian;

      //Create a simple period class to contain all the times in a day
      class day_period : public time_period
      {
      public:
	day_period(date d) : time_period(ptime(d),//midnight
					 ptime(d,hours(24)))
	{}

      };

      int
      main() 
      {

	date d(2002,Feb,1); //an arbitrary date
	//a period that represents a day  
	day_period dp(d);
	ptime t(d, hours(3)+seconds(5)); //an arbitray time on that day
	if (dp.contains(t)) {
	  std::cout << to_simple_string(dp) << " contains "
		    << to_simple_string(t)  << std::endl;
	}
	//a period that represents part of the day
	time_period part_of_day(ptime(d, hours(0)), t);
	//intersect the 2 periods and print the results
	if (part_of_day.intersects(dp)) {
	  time_period result = part_of_day.intersection(dp);
	  std::cout << to_simple_string(dp) << " intersected with\n"
		    << to_simple_string(part_of_day) << " is \n"
		    << to_simple_string(result) << std::endl;
	}
	  
	
	return 0;
      }

    
  

top

PrevUpHomeNext