Show date_time.cc syntax highlighted
#include <iostream>
#include <boost/regex.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <map>
#include <algorithm>
using namespace std;
struct SortableData
{
boost::posix_time::ptime *date;
string from;
};
struct DateCompare : public binary_function<SortableData*, SortableData*,bool>
{
bool operator()(SortableData *a, SortableData *b)
{
return *a->date < *b->date;
}
};
struct FromCompare : public binary_function<SortableData*, SortableData*,bool>
{
bool operator()(SortableData *a, SortableData *b)
{
return a->from < b->from;
}
};
boost::posix_time::ptime mimedate_to_ptime(const std::string &in)
{
std::string out("1969-Jan-01 00:00:00");
std::string year;
std::string zone;
int offset;
// RFC1123 modifies message date header to allow 2 or 4 digit years
boost::regex rfc1123_date("\\w+,\\s(\\d+)\\s(\\w{3})\\s(\\d{2,4})\\s(\\d{1,2}:\\d{1,2}:\\d{1,2})\\s(.*)?", boost::regbase::perl);
boost::smatch matches;
if(boost::regex_match(in, matches, rfc1123_date)) {
year = matches[3].str();
if(year.length() == 2) {
if(year[0] > '6' && year[0] != '0') year = "19" + year;
else year = "20" + year;
}
out = year + "-" + matches[2].str() + "-" + matches[1].str() + " " +
matches[4].str();
}
boost::posix_time::ptime rv(boost::posix_time::time_from_string(out));
// Figure out the time zone offset
zone = matches[5].str();
offset = 0;
if(zone == "EDT") offset = 4*60;
else if(zone == "EST") offset = 5*60;
else if(zone == "CDT") offset = 5*60;
else if(zone == "CST") offset = 6*60;
else if(zone == "MDT") offset = 6*60;
else if(zone == "MST") offset = 7*60;
else if(zone == "PDT") offset = 7*60;
else if(zone == "PST") offset = 8*60;
else if(zone == "M") offset = -12*60;
else if(zone == "Y") offset = +12*60;
else if(zone == "N") offset = -1*60;
else if(zone[0] == '+' || zone[0] == '-') {
offset = atoi(zone.substr(1,2).c_str()) * 60 + atoi(zone.substr(3,2).c_str());
if(zone[0] == '+') offset = -offset;
}
boost::posix_time::time_duration correction;
if(offset > 0) {
correction = boost::posix_time::minutes(offset);
rv = rv + correction;
} else {
correction = boost::posix_time::minutes(-offset);
rv = rv - correction;
}
return rv;
}
int main()
{
string t[4];
string f[4];
int i;
t[0] = string(("Fri, 13 Jun 03 9:36:55 -0700"));
t[1] = string(("Wed, 11 Jun 2003 10:46:55 MST"));
t[2] = string(("Mon, 9 Jun 99 11:36:55 Z"));
t[3] = string(("Wed, 11 Jun 2003 10:38:55 EST"));
f[0] = "tony";
f[1] = "sam";
f[2] = "amanda";
f[3] = "oppenheimer";
SortableData *data[4];
for(i=0; i<4; i++) {
data[i] = new SortableData;
data[i]->date = new boost::posix_time::ptime(mimedate_to_ptime(t[i]));
data[i]->from = f[i];
}
sort(data, data+4,DateCompare());
for(i=0; i<4; i++)
cout << *data[i]->date << endl;
sort(data, data+4,FromCompare());
for(i=0; i<4; i++)
cout << data[i]->from << endl;
}
See more files for this project here