Jonno_FTW
Jonno_FTW

Reputation: 8809

mongocxx: Inserting a Datetime

I'm trying to insert a date and time into mongocxx after parsing a data file, my actual datetime is:

2007/12/01 00:00:00

That is, December 1, 2007 at midnight. I have this code:

static bsoncxx::document::value make_doc(sm_struct const sm) {
    std::tm t{0};
    t.tm_sec = 0;
    t.tm_min=(int)sm.minute;
    t.tm_hour=(int)sm.hour;
    t.tm_mday=(int)sm.day-1;
    t.tm_mon=(int)sm.month;
    t.tm_year=sm.year-1900;
    t.tm_isdst = -1;
    std::time_t tt = mktime(&t);

    std::cout << sm.year << " " << t.tm_year << "/" << t.tm_mon << "/" << t.tm_mday << " " << t.tm_hour << ":" << t.tm_min << std::endl;
    bsoncxx::document::value document = bsoncxx::builder::basic::make_document(
        bsoncxx::builder::basic::kvp("datetime", bsoncxx::types::b_date{
            std::chrono::system_clock::from_time_t(tt)
        }),
    );
    return document;
}

Running my code I get this on stdout:

2007 107/11/31 0:0

When I check my date in the database I get:

ISODate("2007-12-30T13:30:00.000+0000")

How come the hours and minutes are not being set correctly here?

Upvotes: 1

Views: 1603

Answers (1)

Damian
Damian

Reputation: 4631

It looks correct you insert Dec 31, 2007 at midnight local time in Adelaide which is Dec 30, 2007 13:30 (UTC). You can convert the UTC time back to your local time when you show it.

Adelaide, Australia    Mon, 31 Dec 2007 at 00:00 ACDT    
UTC, Time Zone         Sun, 30 Dec 2007 at 13:30         

Source: timeanddate.com

Upvotes: 4

Related Questions