Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get year from boost ptime

I'm converting an existing program to C++ and here need to manipulate Sybase timestamps. These timestamps contain date and time info, which to my knowledge can be best handled by a boost::posix_time::ptime variable. In a few places in the code I need to get the year from the variable.

My question is: how can I most efficiently extract the year from a boost ptime variable? Below is a sample program in which it takes three lines of code, with the overhead of an extra ostringstream variable and a boost::gregorian::date variable.

According to boost documentation:

Class ptime is dependent on gregorian::date for the interface to the date portion of a time point

however gregorian::date doesn't seem to be a base class of ptime. Somehow I'm missing something here.

Isn't there an easier way to extract the year from the ptime?

Sample:

#include <boost/date_time/local_time/local_time.hpp>
#include <iostream>

int main()
{
   boost::posix_time::ptime t(boost::posix_time::second_clock::local_time());
   boost::gregorian::date d = t.date();
   std::ostringstream os; os << d.year();
   std::cout << os.str() << std::endl;
   return 0;
}
like image 538
pointer Avatar asked Sep 12 '09 20:09

pointer


1 Answers

Skip the ostringstream. Otherwise, you may benefit from "using namespace..."

#include <boost/date_time/local_time/local_time.hpp>
#include <iostream>

int main()
{
   using namespace boost::posix_time;
   std::cout << second_clock::local_time().date().year() << std::endl;
   return 0;
}
like image 55
Jonathan Graehl Avatar answered Sep 23 '22 02:09

Jonathan Graehl