efotinis found a good way using from_stream .
I've looked into the manual of date_time
and found it supports facets:
#include <boost/date_time/gregorian/gregorian.hpp>
#include <iostream>
#include <sstream>
#include <locale>
int main() {
using namespace boost::gregorian;
std::wstringstream ss;
wdate_input_facet * fac = new wdate_input_facet(L"%Y-%m-%d");
ss.imbue(std::locale(std::locale::classic(), fac));
date d;
ss << L"2004-01-01 2005-01-01 2006-06-06";
while(ss >> d) {
std::cout << d << std::endl;
}
}
You could also go with that.
I've looked up how date facets work:
- The
boost::date_time::date_input_facet
template implements a facet. - Facets are derived from
std::locale::facet
and every one has an unique id. - You can imbue a new locale into a stream, replacing its old locale. The locale of a stream will be used for all sorts of parsing and conversions.
- When you create a new
std::locale
using the form i showed, you give it an existing locale, and a pointer to facet. The given facet will replace any existing facet of the same type in the locale given. (so, it would replace any other date_input_facet used). - All facets are associated with the locale somehow, so that you can use
std::has_facet<Facet>(some_locale)
to check whether the given locale has some given facet type. - You can use a facet from one locale by doing
std::use_facet<Facet>(some_locale).some_member...
. - date_input_facet has a function get, which can be used like this:
The below is essentially done by operator>>
by boost::date_type :
// assume src is a stream having the wdate_input_facet in its locale.
// wdate_input_facet is a boost::date_time::date_input_facet<date,wchar_t> typedef.
date d;
// iterate over characters of src
std::istreambuf_iterator<wchar_t> b(src), e;
// use the facet to parse the date
std::use_facet<wdate_input_facet>(src.getloc()).get(b, e, src, d);
Johannes Schaub - litb
2008-11-29 16:35:35