Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining integer representation of boost::gregorian::date

Tags:

c++

date

boost

From boost documentation on class boost::gregorian::date here:

"Internally boost::gregorian::date is stored as a 32 bit integer type"

Now that would be a nice, compact way to, say, store this date in a file. But the doc doesn't specify any way to extract it from the object.

The question is: Is there a way to obtain this integer representation, to later construct another, equal, object of the same class?

like image 993
Cássio Renan Avatar asked Sep 30 '22 14:09

Cássio Renan


1 Answers

The day_number() member function returns this.

boost::gregorian::date d(2014, 10, 18);
uint32_t number = d.day_number();

The inverse can be achieved:

gregorian_calendar::ymd_type ymd = gregorian_calendar::from_day_number(dn);
d = { ymd.year, ymd.month, ymd.day };

You can of course use Boost Serialization to serialize, and it will use the most compact representation. See http://www.boost.org/doc/libs/1_56_0/doc/html/date_time/serialization.html

See full demo: Live On Coliru

#include <boost/date_time/gregorian/greg_date.hpp>
#include <boost/date_time/gregorian/gregorian_io.hpp>
#include <iostream>

using namespace boost::gregorian;

int main()
{
    date d(2014, 10, 17);
    static_assert(sizeof(d) == sizeof(int32_t), "truth");

    std::cout << d << "\n";

    uint32_t dn = d.day_number();
    dn += 1;

    gregorian_calendar::ymd_type ymd = gregorian_calendar::from_day_number(dn);
    d = { ymd.year, ymd.month, ymd.day };
    std::cout << d << "\n";
}
like image 86
sehe Avatar answered Oct 03 '22 06:10

sehe