mirror of
https://github.com/HowardHinnant/date.git
synced 2025-08-06 06:04:27 +02:00
Updated Boost datetime Examples Translated (markdown)
@@ -32,7 +32,7 @@ look if ported to this library.
|
|||||||
#include <cassert>
|
#include <cassert>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
#include <stdexcept>
|
#include <exception>
|
||||||
|
|
||||||
int
|
int
|
||||||
main()
|
main()
|
||||||
@@ -42,40 +42,26 @@ look if ported to this library.
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
// The following date is in ISO 8601 extended format (CCYY-MM-DD)
|
// The following date is in ISO 8601 extended format (CCYY-MM-DD)
|
||||||
string s("2001-10-9"); // 2001-October-09
|
istringstream in{"2001-10-9"}; // 2001-October-09
|
||||||
istringstream in(s);
|
year_month_day d;
|
||||||
int y, m, day;
|
in >> parse("%F", d);
|
||||||
char dash;
|
|
||||||
in >> y >> dash >> m >> dash >> day;
|
|
||||||
auto d = year(y)/m/day;
|
|
||||||
assert(d.ok());
|
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
|
// Read ISO Standard(CCYYMMDD) and output ISO Extended
|
||||||
string ud("20011009"); // 2001-Oct-09
|
in.str("20011009"); // 2001-Oct-09
|
||||||
auto d1 = year(stoi(ud.substr(0, 4)))/stoi(ud.substr(4, 2))
|
in >> parse("%Y%m%d", d);
|
||||||
/stoi(ud.substr(6, 2));
|
assert(d.ok());
|
||||||
assert(d1.ok());
|
cout << d << '\n'; // 2001-10-09
|
||||||
cout << d1 << '\n'; // 2001-10-09
|
|
||||||
|
|
||||||
// Output the parts of the date - Tuesday October 9, 2001
|
// Output the parts of the date - Tuesday October 9, 2001
|
||||||
auto wd = weekday{d1};
|
cout << format("%A %B %e, %Y\n", d);
|
||||||
cout << wd << ' ' << d1.month() << ' '
|
|
||||||
<< static_cast<unsigned>(d1.day())
|
|
||||||
<< ", " << d1.year() << '\n'; // Tue Oct 9, 2001
|
|
||||||
|
|
||||||
// Let's send in month 25 by accident and create an exception
|
// 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";
|
cout << "An expected exception is next:\n";
|
||||||
auto d2 = year(stoi(bad_date.substr(0, 4)))
|
in >> parse("%Y%m%d", d);
|
||||||
/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());
|
|
||||||
}
|
|
||||||
cout << "oh oh, you shouldn't reach this line:\n";
|
cout << "oh oh, you shouldn't reach this line:\n";
|
||||||
}
|
}
|
||||||
catch (const exception& e)
|
catch (const exception& e)
|
||||||
|
Reference in New Issue
Block a user