Get a year from ptime increase

I am converting an existing program into C ++ and here I need to manipulate Sybase timestamps. These timestamps contain date and time information, which, as far as I know, can be best processed by a variable boost::posix_time::ptime. In several places in the code, I need to get the year from the variable.

My question is: how can I most effectively extract the year from the ptime boost variable? The following is an example of a program in which it takes three lines of code with the overhead of an additional variable ostringstreamand a variable boost::gregorian::date.

According to additional documentation:

The ptime class is dependent on gregorian::datefor an interface with a date part time

however, gregorian::dateit is not a base class ptime. Somehow I missed something here.

Is there an easier way to extract a year from ptime?

Example:

#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;
}
+5
source share
1 answer

Skip pointy stream. Otherwise, you can use "using the 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;
}
+5
source

All Articles