month_add.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /* Simple program that uses the gregorian calendar to progress by exactly
  2. * one month, regardless of how many days are in that month.
  3. *
  4. * This method can be used as an alternative to iterators
  5. */
  6. #include "boost/date_time/gregorian/gregorian.hpp"
  7. #include <iostream>
  8. int
  9. main()
  10. {
  11. using namespace boost::gregorian;
  12. date d = day_clock::local_day();
  13. date d2 = d + months(1);
  14. date d3 = d - months(1);
  15. std::cout << "Today is: " << to_simple_string(d) << ".\n"
  16. << "One month from today will be: " << to_simple_string(d2) << ".\n"
  17. << "One month ago was: " << to_simple_string(d3)
  18. << std::endl;
  19. std::cout << "******** Warning read this ***********************\n";
  20. std::cout << "Be aware that adding a month is not exactly like regular numeric math.\n"
  21. << "Addition/Subtraction of months will 'snap to the end' of a month that\n"
  22. << "is shorter than the current month. For example consider "
  23. << "Jan 31, 2004 + (1 month)\n";
  24. date d4(2004, Jan, 31);
  25. date d5 = d4 + months(1);
  26. std::cout << "Result is: " << to_simple_string(d5)
  27. << std::endl;
  28. std::cout << "\nSo what does this mean? It means the result of adding months is order\n"
  29. << "dependent, non-commutative, and may create problems for applications.\n"
  30. << "Consider: \n"
  31. << "Jan 30, 2004 + (1 month) + (1 month) != Jan 30, 2004 + (2 months)\n"
  32. << "Why not? Because Jan 30, 2004 + 1 month is Feb 29 + 1 month is Mar 31st.\n"
  33. << "while Jan 30, 2004 + 2 months is Mar 30th.\n"
  34. << "All of this clears up as long as all the starting dates before the 28th of\n"
  35. << "the month -- then all the behavior follows classical mathematical rules.\n";
  36. date d6(2004, Jan, 30);
  37. date d7 = d6 + months(1) + months(1);
  38. date d8 = d6 + months(2);
  39. std::cout << "2004-01-30 + (1 month) + (1 month) is: " << to_simple_string(d7) << ".\n"
  40. << "2004-01-30 + (2 months) is: " << to_simple_string(d8)
  41. << std::endl;
  42. return 0;
  43. }
  44. /* Copyright 2001-2005: CrystalClear Software, Inc
  45. * http://www.crystalclearsoftware.com
  46. *
  47. * Subject to the Boost Software License, Version 1.0.
  48. * (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
  49. */