views:

412

answers:

1

Hi,

This is my first post on stackoverflow. First of all I'd like to say thanks for this site! It has provided many excellent answers to questions I've had in the past few months. I'm still learning C++, coming from vb6. 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 knowledgde 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;
}
+3  A: 

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;
}
wrang-wrang