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