dates_as_strings.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* The following is a simple example that shows conversion of dates
  2. * to and from a std::string.
  3. *
  4. * Expected output:
  5. * 2001-Oct-09
  6. * 2001-10-09
  7. * Tuesday October 9, 2001
  8. * An expected exception is next:
  9. * Exception: Month number is out of range 1..12
  10. */
  11. #include "boost/date_time/gregorian/gregorian.hpp"
  12. #include <iostream>
  13. #include <string>
  14. int
  15. main()
  16. {
  17. using namespace boost::gregorian;
  18. try {
  19. // The following date is in ISO 8601 extended format (CCYY-MM-DD)
  20. std::string s("2001-10-9"); //2001-October-09
  21. date d(from_simple_string(s));
  22. std::cout << to_simple_string(d) << std::endl;
  23. //Read ISO Standard(CCYYMMDD) and output ISO Extended
  24. std::string ud("20011009"); //2001-Oct-09
  25. date d1(from_undelimited_string(ud));
  26. std::cout << to_iso_extended_string(d1) << std::endl;
  27. //Output the parts of the date - Tuesday October 9, 2001
  28. date::ymd_type ymd = d1.year_month_day();
  29. greg_weekday wd = d1.day_of_week();
  30. std::cout << wd.as_long_string() << " "
  31. << ymd.month.as_long_string() << " "
  32. << ymd.day << ", " << ymd.year
  33. << std::endl;
  34. //Let's send in month 25 by accident and create an exception
  35. std::string bad_date("20012509"); //2001-??-09
  36. std::cout << "An expected exception is next: " << std::endl;
  37. date wont_construct(from_undelimited_string(bad_date));
  38. //use wont_construct so compiler doesn't complain, but you wont get here!
  39. std::cout << "oh oh, you shouldn't reach this line: "
  40. << to_iso_string(wont_construct) << std::endl;
  41. }
  42. catch(std::exception& e) {
  43. std::cout << " Exception: " << e.what() << std::endl;
  44. }
  45. return 0;
  46. }
  47. /* Copyright 2001-2004: CrystalClear Software, Inc
  48. * http://www.crystalclearsoftware.com
  49. *
  50. * Subject to the Boost Software License, Version 1.0.
  51. * (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
  52. */