Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set values (year, month, day...) in a boost::posix_time

In a class, I have an attribute boost::posix_time::ptime that refers to a date and time like this:

boost::posix_time::ptime p_;

In the constructor, I can pass the values and set them without problems.

my_class::my_class( ... )
  : p_( boost::posix_time::ptime( boost::gregorian::date(y,M,d),
                                  hours(h) + minutes(m) + seconds(s) +
                                  milliseconds(ms) + microseconds(us) +
                                  nanosec(ns));

I would like to create set methods (add and subtract) the values for all fields of this ptime (year, month, day, hours... if possible).

If I use the ptime_.date(), it returns a cons reference of date, and I can't set it directly.

I'd like to do something like this:

void my_class::set_year(qint64 y) {
  // p_.date().year = y;
}

Is this possible?

I was thinking on creating a reset(...) method, and set what I need, but it sounds weird for this purpose (copy all values and repeat them in the code).

Rgds.

like image 650
Etore Marcari Jr. Avatar asked Mar 20 '23 21:03

Etore Marcari Jr.


1 Answers

In description of boost ptime we can read:

The class boost::posix_time::ptime is the primary interface for time point manipulation. In general, the ptime class is immutable once constructed although it does allow assignment. (...) Functions for converting posix_time objects to, and from, tm structs are provided as well as conversion from time_t and FILETIME.

So conversion to time struct tm and from it can be used. This snippet demonstrates this.

#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/date.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
/*
 * 
 */

using namespace boost::posix_time;
using namespace boost::gregorian;

void set_year( uint64_t y, ptime& p) {
    tm pt_tm = to_tm( p);
    pt_tm.tm_year = y - 1900;
    p = ptime_from_tm( pt_tm);
}

int main(int argc, char** argv) {
   ptime t1( date(2002,Feb,10), hours(5)+minutes(4)+seconds(2)); 
   std::cout << to_simple_string( t1) << std::endl;
   set_year( 2001, t1);
   std::cout << to_simple_string( t1);
}

output:

2002-Feb-10 05:04:02

2001-Feb-10 05:04:02

like image 149
4pie0 Avatar answered Mar 23 '23 00:03

4pie0