I'm writing a kind of HTTP proxy, so I need to be able to do 3 things:
- Parse an HTTP-date given any of the 3 formats specified in RFC 2616, sec 3.3,
- Convert a file date-time to an HTTP-date string, and
- Output the date to a string.
For reference, theses are examples of the date-times I need to parse. I will output only the first format:
Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
I'm pretty sure Boost date_time can do all of this, but I'm having some trouble with number 1. Does anyone already have code to do this? Perhaps I'm not using google proficiently, but I can't find an example of how to do this with boost anywhere.
Thanks for any help!
UPDATE: I have a solution, but the second parser has the wrong year (I guess because it is a 2 digit year) and the last parser gives an exception (see output below).
try
{
// output time now in GMT
// format we want: Sun, 06 Nov 1994 08:49:37 GMT
boost::local_time::local_date_time t(boost::local_time::local_sec_clock::local_time(boost::local_time::time_zone_ptr()));
boost::local_time::local_time_facet* lf(new boost::local_time::local_time_facet("%a, %d %b %Y %H:%M:%S GMT"));
std::cout.imbue(std::locale(std::cout.getloc(), lf));
std::cout << t << std::endl;
// get a file mod time into the correct format
boost::filesystem::path p("../code/main.cpp");
boost::posix_time::ptime pt = boost::posix_time::from_time_t(
boost::filesystem::last_write_time(p));
boost::local_time::local_date_time t2(pt, boost::local_time::time_zone_ptr());
std::cout << t2 << std::endl;
std::stringstream ss;
ss.exceptions(std::ios_base::failbit);
// input date-time
boost::local_time::local_time_input_facet* lif1(new boost::local_time::local_time_input_facet("%a, %d %b %Y %H:%M:%S GMT"));
ss.imbue(std::locale(std::locale::classic(), lif1));
ss.str("Sun, 06 Nov 1994 08:49:37 GMT");
ss >> t;
std::cout << t << std::endl;
boost::local_time::local_time_input_facet* lif2(new boost::local_time::local_time_input_facet("%A, %d-%b-%y %H:%M:%S GMT"));
ss.imbue(std::locale(std::locale::classic(), lif2));
ss.str("Sunday, 06-Nov-94 08:49:37 GMT");
ss >> t;
std::cout << t << std::endl;
boost::local_time::local_time_input_facet* lif3(new boost::local_time::local_time_input_facet("%a %b %e %H:%M:%S %Y"));
ss.imbue(std::locale(std::locale::classic(), lif3));
ss.str("Sun Nov 6 08:49:37 1994");
ss >> t;
std::cout << t << std::endl;
}
catch (std::exception& e)
{
std::cout << "Exception: " << e.what() << std::endl;
}
Output:
Sat, 15 May 2010 03:01:13 GMT
Sat, 15 May 2010 03:01:01 GMT
Sun, 06 Nov 1994 08:49:37 GMT
Sat, 06 Nov 2094 08:49:37 GMT
Exception: Parse failed. No match found for ''