Not a real meerkat
Not a real meerkat

Reputation: 5729

Obtaining integer representation of boost::gregorian::date

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?

Upvotes: 5

Views: 1739

Answers (2)

sehe
sehe

Reputation: 392911

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

Upvotes: 5

Oncaphillis
Oncaphillis

Reputation: 1908

A cheep trick would be to do

tm to_tm(date)

and

date date_from_tm(tm datetm)

and transform the tm from/to time_t with

struct tm *localtime(const time_t *timep); time_t mktime(struct tm *tm)

time_t however often is 64 bit and the old 32 bit will fail in the year 2038.

It's not to complicated to encode/decode the date as

int32_t  ye = d.year(); 
uint32_t mo = d.month(); 
uint32_t da = d.day();

// encode
int32_t l = ((ye << 9) & 0xfffffe00) | ((mo << 5) & 0x0000001d0) | (da & 0x0000001f);

// decode 
ye = (l  >> 9); 
mo = ((l >> 5) & 0x0000000f); 
da = (l        & 0x0000001f); 

Upvotes: 0

Related Questions