period_calc.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. This example demonstrates a simple use of periods for the calculation
  3. of date information.
  4. The example calculates if a given date is a weekend or holiday
  5. given an exclusion set. That is, each weekend or holiday is
  6. entered into the set as a time interval. Then if a given date
  7. is contained within any of the intervals it is considered to
  8. be within the exclusion set and hence is a offtime.
  9. Output:
  10. Number Excluded Periods: 5
  11. 20020202/20020203
  12. 20020209/20020210
  13. 20020212/20020212
  14. 20020216/20020217
  15. In Exclusion Period: 20020216 --> 20020216/20020217
  16. 20020223/20020224
  17. */
  18. #include "boost/date_time/gregorian/gregorian.hpp"
  19. #include <set>
  20. #include <algorithm>
  21. #include <iostream>
  22. typedef std::set<boost::gregorian::date_period> date_period_set;
  23. //Simple population of the exclusion set
  24. date_period_set
  25. generateExclusion()
  26. {
  27. using namespace boost::gregorian;
  28. date_period periods_array[] =
  29. { date_period(date(2002,Feb,2), date(2002,Feb,4)),//weekend of 2nd-3rd
  30. date_period(date(2002,Feb,9), date(2002,Feb,11)),
  31. date_period(date(2002,Feb,16), date(2002,Feb,18)),
  32. date_period(date(2002,Feb,23), date(2002,Feb,25)),
  33. date_period(date(2002,Feb,12), date(2002,Feb,13))//a random holiday 2-12
  34. };
  35. const int num_periods = sizeof(periods_array)/sizeof(date_period);
  36. date_period_set ps;
  37. //insert the periods in the set
  38. std::insert_iterator<date_period_set> itr(ps, ps.begin());
  39. std::copy(periods_array, periods_array+num_periods, itr );
  40. return ps;
  41. }
  42. int main()
  43. {
  44. using namespace boost::gregorian;
  45. date_period_set ps = generateExclusion();
  46. std::cout << "Number Excluded Periods: " << ps.size() << std::endl;
  47. date d(2002,Feb,16);
  48. date_period_set::const_iterator i = ps.begin();
  49. //print the periods, check for containment
  50. for (;i != ps.end(); i++) {
  51. std::cout << to_iso_string(*i) << std::endl;
  52. //if date is in exclusion period then print it
  53. if (i->contains(d)) {
  54. std::cout << "In Exclusion Period: "
  55. << to_iso_string(d) << " --> " << to_iso_string(*i)
  56. << std::endl;
  57. }
  58. }
  59. return 0;
  60. }
  61. /* Copyright 2001-2004: CrystalClear Software, Inc
  62. * http://www.crystalclearsoftware.com
  63. *
  64. * Subject to the Boost Software License, Version 1.0.
  65. * (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
  66. */