【问题标题】:can boost gregorian date and boost posix time properly calculate unixtime?可以提高公历日期和提高posix时间正确计算unixtime吗?
【发布时间】:2013-02-07 11:11:01
【问题描述】:

我正在尝试编写一个简单的时间戳系统,它提供从当前时间开始的纪元秒和小数秒。我正在使用 boost 库并且有这样的东西:

const boost::posix_time::ptime epoch(boost::gregorian::date(1970, 1, 1));
boost::posix_time::ptime time() {
    boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
    return now;
}
boost::posix_time::time_duration dur = (time() - epoch);

然后使用以下元素提取纪元值:

dur.total_seconds();
dur.fractional_seconds();

具体来说,这会返回正确的 unix 时间吗?如果没有,关于如何纠正它的任何建议?谢谢。

【问题讨论】:

    标签: c++ date boost timestamp unix-timestamp


    【解决方案1】:

    是的,这应该可行,但可以肯定的是,总是有实验证据:

    #include <iostream>
    #include <time.h>
    #include <boost/date_time.hpp>
    namespace bpt = boost::posix_time;
    namespace bg = boost::gregorian;
    int main()
    {
        bpt::time_duration dur = bpt::microsec_clock::universal_time()
                               - bpt::ptime(bg::date(1970, 1, 1));
        timespec ts;
        clock_gettime(CLOCK_REALTIME, &ts);
        std::cout << std::setfill('0')
                  << " boost: " << dur.total_seconds() << '.' << std::setw(6)
                                << dur.fractional_seconds() << '\n'
                  << " ctime: " << time(NULL) << '\n'
                  << " posix: " << ts.tv_sec << '.' << std::setw(9)
                                << ts.tv_nsec << '\n';
    }
    

    我明白了

    Linux/gcc

     boost: 1361502964.664746
     ctime: 1361502964
     posix: 1361502964.664818326
    

    太阳/太阳工作室

     boost: 1361503762.775609
     ctime: 1361503762
     posix: 1361503762.775661600
    

    AIX/XLC

     boost: 1361503891.342930
     ctime: 1361503891
     posix: 1361503891.342946000
    

    甚至是 Windows/Visual Studio

     boost: 1361504377.084231
     ctime: 1361504377
    

    看起来他们都同意自 date(1970,1,1) 以来经过了多少秒

    【讨论】:

    • 运行实验的要点,感谢不同系统上的结果,这很有帮助。我应该提到我是在 Linux/gcc 和 windows/vs2010 上构建的。
    猜你喜欢
    • 1970-01-01
    • 2018-10-21
    • 2016-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    相关资源
    最近更新 更多