Thanks Jeff for the detailed example.
Eagerly looking forward to the 1.33 release.
--- Jeff Garland
Hi, I was going through the API to parse a date-time field. I came across the boost library regarding
On Sun, 19 Dec 2004 22:22:46 -0800 (PST), Rakesh Kumar wrote the
same.
#include "boost/date_time/posix_time/posix_time.hpp"
using namespace boost::posix_time; #include <iostream> #include <cstdlib>
using std::cout;
int main() { std::string ts("2002-01-20 23:59:59.000"); ptime t(time_from_string(ts));
cout << to_simple_string(t); return EXIT_SUCCESS; }
This example compiled fine and gave me the right results. But suppose if I have another date representation as follows.
06 Dec 2004 10:40:58.000
If I enter the same string and try to parse from it, the method time_from_string aborts. I was wondering if there is any way I can tell time_from_string the format and try to parse from it.
Well, there isn't currently a way to tell from_string to do this directly. However, you can use functions from the library to write your own parsing routine. For example, the following handles the format you provided:
boost::posix_time::ptime my_parse_time(const std::string& s) { using namespace boost::gregorian; using namespace boost::posix_time; std::string date_part(s.substr(0,11)); date d = from_uk_string(date_part); //expects day month year order std::string time_part(s.substr(12,12)); time_duration td = duration_from_string(time_part); return ptime(d, td); }
int main() { using namespace boost::posix_time; using namespace boost::gregorian; std::string ts("06 Dec 2004 23:59:59.000"); try { ptime t = my_parse_time(ts); std::cout << to_simple_string(t) << std::endl; } catch(std::exception& e) {} // invalid time string return 0;
}
In the 1.33 release you will be able to pass a format to a facet class to adjust how you want things parsed. It will look like this:
std::stringstream ss("06 Dec 2004 23:59:59.000"); time_facet* tf = new time_facet("%d %M %Y %H:%M:%s"); ss.imbue(tf); ptime t; //not-a-date-time ss >> t;
Jeff _______________________________________________ Boost-users mailing list Boost-users@lists.boost.org
http://lists.boost.org/mailman/listinfo.cgi/boost-users
__________________________________ Do you Yahoo!? Yahoo! Mail - now with 250MB free storage. Learn more. http://info.mail.yahoo.com/mail_250