在boost :: posix_time :: ptime和mongo :: Date_t之间转换

时间:2012-06-11 01:58:17

标签: c++ datetime mongodb boost

是否有一种简洁的方法或一种普遍接受的方式从boost::posix_time::ptime转换为mongo::Date_t并再次返回?

Mongo to Boost

Boost documentation似乎不完整或不正确。它记录了一个函数date_from_tm,它从date构造了一个tm结构。但是,给出了以下示例:

tm pt_tm;
/* snip */
ptime pt = ptime_from_tm(pt_tm);

但是没有记录的函数ptime_from_tm。但是this header file 确实包含该功能。

所以,我至少可以从mongo::Date_t转到boost::posix_time::ptime

mongo::Date_t d = ...;
std::tm t;
d.toTm(&t);
boost::posix_time::ptime pt = ptime_from_tm(t);

升级为Mongo

当涉及到相反的方向时,我有点卡住了。 MongoDB documentation相当不完整,关联的header file没有很多有用的评论。基本上,Date_t结构由unsigned long long毫秒计数构成。我只能从1970-1-1:00:00.00纪元假设

所以我目前从boost::posix_time::ptime转到mongo::Date_t的解决方案是:

boost::posix_time::ptime pt = ...;
std::tm pt_tm = boost::posix_time::to_tm(pt);
std::time_t t = mktime(pt_tm);
mongo::Date_t d(t);

当然,我可能会将其折叠成一行,但似乎从一个日期/时间表示到另一个再返回的整个往返行程变得令人费解和混乱。

最后

有更好的方法吗?有没有更好的图书馆知识和对日期/时间编程有更好理解的人知道一种简洁,简单的方法来实现我想要实现的目标吗?

2 个答案:

答案 0 :(得分:3)

似乎你的解决方案从ptime转换为Date_t有一些问题,我尝试它并得到不正确的结果,因为我评论。 我有更好的方法:

mongo::Date_t convert(const boost::posix_time::ptime& time)
{
    boost::posix_time::ptime epoch(boost::gregorian::date(1970,boost::date_time::Jan,1));
    boost::posix_time::time_duration d = time - epoch;
    return mongo::Date_t(d.total_milliseconds());
}
boost::posix_time::ptime convert(const mongo::Date_t& time)
{
    boost::posix_time::ptime epoch(boost::gregorian::date(1970,boost::date_time::Jan,1));
    boost::posix_time::time_duration d = boost::posix_time::milliseconds(time.millis);//- epoch;
    return boost::posix_time::ptime(epoch+d);
}

请注意,2.4.3(据我所知)Date_t :: toString()有bug,'date'已经增加了8个小时。您可以在here

处验证“总毫秒数”

答案 1 :(得分:2)

  

基本上,Date_t结构是从无符号长long毫秒计数构造的。我只能从1970-1-1:00:00.00纪元假设

你是对的。

我认为您的代码与您将获得的代码一样好。你必须以某种方式达到time_t-like-from-the epoch,这似乎是a little complex与ptime。