[date_time] How to parse "5th" into day of month?
Hi all, I'm a bit stuck with the date_time module. I found a few examples (ironically from bug reports) since I couldn't find any on the Boost documentation site, as I am trying to parse a string in the format "Fri 5th March 2010, 05:01pm" into a boost::gregorian::date structure. Unfortunately I can't figure out how to get it to recognise "5th". It works fine if the day is two digits, but for a single digit it returns the error "Day of month value is out of range 1..31" My date string is "%a %e.. %B %Y" (not sure if the ".." is correct but it was the only way I could get it to ignore the "th" after the day - again, I couldn't find anything about doing that in the docs.) Does anyone know whether it's possible to parse a date with a single digit day in it? Some of the docs hint that it's possible and give sample dates in that format, but they don't include the matching format specifiers to use. Here is my code: std::string strDate = "Fri 5th March 2010, 05:01pm"; std::string format("%a %e.. %B %Y"); boost::date_time::format_date_parser<boost::gregorian::date, char> parser(format, std::locale("C")); boost::date_time::special_values_parser<boost::gregorian::date, char> svp; boost::gregorian::date d = parser.parse_date(strDate, format, svp); std::cout << "Converted date from \"" << strDate << "\" to " << d << std::endl; Any suggestions would be much appreciated, or pointers to the correct documentation because I'm having real trouble finding where this sort of thing is explained :-( Many thanks, Adam.
Just to follow up on this, I've come up with a rather dodgy workaround for this:
Here is my code:
std::string strDate = "Fri 5th March 2010, 05:01pm"; std::string format("%a %e.. %B %Y");
The line above becomes this, which is used to select a different date format depending on whether the day is a single digit or double digit: std::string format; if ((strDate[5] < '0') || (strDate[5] > '9')) { // Single-digit day format = "%a%e.. %B %Y"; } else { // Double-digit day format = "%a %d.. %B %Y"; }
boost::date_time::format_date_parser<boost::gregorian::date, char> parser(format, std::locale("C")); boost::date_time::special_values_parser<boost::gregorian::date, char> svp; boost::gregorian::date d = parser.parse_date(strDate, format, svp);
std::cout << "Converted date from \"" << strDate << "\" to " << d << std::endl;
Seems somewhat of an odd omission that a library with such a strong emphasis on reading dates from strings would be unable to handle numbers of different lengths. I'm sure I'm missing something but I still can't find anything that explains how to achieve this elegantly! Cheers, Adam.
participants (1)
-
Adam Nielsen