ex_dates_as_strings.xml 2.3 KB

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