Updated Boost datetime Examples Translated (markdown)

Howard Hinnant
2017-07-07 16:46:57 -04:00
parent 521e532e41
commit 840eabf15a

@@ -32,7 +32,7 @@ look if ported to this library.
#include <cassert>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <exception>
int
main()
@@ -42,40 +42,26 @@ look if ported to this library.
try
{
// The following date is in ISO 8601 extended format (CCYY-MM-DD)
string s("2001-10-9"); // 2001-October-09
istringstream in(s);
int y, m, day;
char dash;
in >> y >> dash >> m >> dash >> day;
auto d = year(y)/m/day;
istringstream in{"2001-10-9"}; // 2001-October-09
year_month_day d;
in >> parse("%F", d);
assert(d.ok());
cout << d.year() << '-' << d.month() << '-' << d.day() << '\n';
cout << format("%Y-%b-%d\n", d);
// Read ISO Standard(CCYYMMDD) and output ISO Extended
string ud("20011009"); // 2001-Oct-09
auto d1 = year(stoi(ud.substr(0, 4)))/stoi(ud.substr(4, 2))
/stoi(ud.substr(6, 2));
assert(d1.ok());
cout << d1 << '\n'; // 2001-10-09
in.str("20011009"); // 2001-Oct-09
in >> parse("%Y%m%d", d);
assert(d.ok());
cout << d << '\n'; // 2001-10-09
// Output the parts of the date - Tuesday October 9, 2001
auto wd = weekday{d1};
cout << wd << ' ' << d1.month() << ' '
<< static_cast<unsigned>(d1.day())
<< ", " << d1.year() << '\n'; // Tue Oct 9, 2001
cout << format("%A %B %e, %Y\n", d);
// Let's send in month 25 by accident and create an exception
string bad_date("20012509"); // 2001-??-09
in.str("20012509"); // 2001-??-09
in.exceptions(std::ios::failbit);
cout << "An expected exception is next:\n";
auto d2 = year(stoi(bad_date.substr(0, 4)))
/stoi(bad_date.substr(4, 2))
/stoi(bad_date.substr(6, 2));
if (!d2.ok())
{
ostringstream msg;
msg << "Invalid date: " << d2;
throw runtime_error(msg.str());
}
in >> parse("%Y%m%d", d);
cout << "oh oh, you shouldn't reach this line:\n";
}
catch (const exception& e)