Converting from std::chrono::system_clock::time_point to b_date and back

90 views
Skip to first unread message

Ofer Reichman

unread,
Sep 25, 2015, 4:08:37 AM9/25/15
to mongodb-user
I've spent some time trying to figure out how to store a time_point using the C++ driver.
I'm posting my code for review and to help anyone who might need it (until the driver supports it).

Storing:
using std::chrono::system_clock;
using std::chrono::duration_cast;
using std::chrono::milliseconds;

system_clock::time_point tp = system_clock::now(); // for example

document << "someTimePoint" << b_date{duration_cast<milliseconds>(tp.time_since_epoch()).count()};

Retrieving:
system_clock::time_point tp(duration_cast<system_clock::duration>(milliseconds{doc->view()["someTimePoint"].get_date().value}));

Note: Different clocks have different epochs, so this code may not work correctly if the machine that stores the time_point is different than the one that retrieves it.

Hope this is helpful.
Any reviews are welcome!

Ofer

Adam Midvidy

unread,
Sep 25, 2015, 10:35:27 AM9/25/15
to mongodb-user
Hi Ofer,

Thanks for sharing this. If you'd like to add a constructor to b_date that takes a std::chrono::system_clock::time_point, we'd be happy to take a pull request for it. We have an outstanding ticket for this: https://jira.mongodb.org/browse/CXX-626.

Thanks,
Adam

Ofer Reichman

unread,
Sep 29, 2015, 8:03:18 AM9/29/15
to mongodb-user
Would be happy to do so, once I get some reviews. I'm not sure I'm doing it right.
According to the manual, "BSON Date is a 64-bit integer that represents the number of milliseconds since the Unix epoch (Jan 1, 1970)."  So I think I got that right.
Is using the type system_clock::time_point correct?
Is the C++ code optimal? (especially the 2nd one - retrieval)

Ofer Reichman

unread,
Oct 8, 2015, 12:37:22 PM10/8/15
to mongodb-user
done. added constructor and casting operator to b_date.
Reply all
Reply to author
Forward
0 new messages