Here is a sample tweet timestamp as requested through their API.
Thu Jun 09 00:06:02 +0000 2011
In order to parse this tweet using the Boost Date Time library, we can use the following code.
#define BOOST_ALL_DYN_LINK
#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_duration.hpp>
#include <boost/date_time/c_local_time_adjustor.hpp>
int main()
{
using namespace boost::posix_time;
std::string format = "%a %b %d %H:%M:%S +0000 %Y";
std::string tweetTimeString = "Thu Jun 08 00:06:02 +0000 2011";
ptime tweetTime;
time_input_facet facet(format, 1);
std::stringstream ss(tweetTimeString);
ss.imbue(std::locale(ss.getloc(), &facet));
ss >> tweetTime;
std::cout << "Time: " << tweetTime << std::endl;
typedef boost::date_time::c_local_adjustor<ptime> local_adj;
ptime adjusted = local_adj::utc_to_local(tweetTime);
std::cout << "Adjusted for time zone: " << adjusted << std::endl;
ptime now(second_clock::local_time());
time_duration elapsed = now - adjusted;
std::stringstream elapsedString;
if (elapsed.hours() < 1)
elapsedString << elapsed.minutes() << " minutes";
else
elapsedString << elapsed.hours() << " hours";
std::cout << "Time elapsed since then: " << elapsedString.str() << std::endl;
}
The output is
Time: 2011-Jun-09 00:06:02
Adjusted for time zone: 2011-Jun-08 20:06:02
Time elapsed since then: 55 minutes
Press any key to continue . . .
Pretty neat, isn’t it? The code is pretty readable, too. The adjustment I’m talking about is a translation from UTC to my local timezone which is EDT. I have not found a good way to deal with the UTC offset, but from what I can tell, Twitter will always give me UTC timestamps, which is why I just hardcoded +0000 into the format string. I might have to fix this later though.
Advertisement