c++ - Boost C++ date_time microsec_clock 和 second_clock

标签 c++ datetime boost utc clock

我在 Boost C++ 日期时间库中发现了一个奇怪的结果。 microsec_clocksecond_clock 之间存在不一致,我不明白为什么会这样。我使用的是 Windows XP 32 位

我的代码片段:

using namespace boost::posix_time;
...
ptime now = second_clock::universal_time();
std::cout << "Current Time is: "<< to_iso_extended_string(now)<< std::endl;
ptime now_2 = microsec_clock::universal_time();
std::cout << "Current Time is: "<< to_iso_extended_string(now_2)<< std::endl;
...

我期望的打印输出是没有毫秒和毫秒的当前时间。但是,我的电脑中有:

2009-10-14T16:07:38  
1970-06-24T20:36:09.375890

我不明白为什么我的 microsec_clock 时间里有一个奇怪的日期(1970 年???)。 Boost 的相关文档:link to boost date time

最佳答案

不确定您可能出了什么问题;完全相同的代码对我有用。

$ cat > test.cc
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace boost::posix_time;
int main() {
    ptime now = second_clock::universal_time();
    std::cout << "Current Time is: "<< to_iso_extended_string(now)<< std::endl;
    ptime now_2 = microsec_clock::universal_time();
    std::cout << "Current Time is: "<< to_iso_extended_string(now_2)<< std::endl;
    return 0;
}
^D
$ c++ -lboost_date_time test.cc
$ ./a.out
Current Time is: 2009-10-14T16:26:55
Current Time is: 2009-10-14T16:26:55.586295

实现方面,second_clock 使用 time microsec_clock 使用 gettimeofdayGetSystemTimeAsFileTime下面,取决于平台。您的平台似乎有问题 - 您的操作系统和版本是什么?


您的 Boost 版本是什么?如果是 1.38 或更低版本,请升级到 1.39 或将修复应用到 #2809手动。

--- boost/date_time/filetime_functions.hpp  (revision 53621)
+++ boost/date_time/filetime_functions.hpp  (revision 53622)
@@ -96,9 +96,7 @@
     {
         /* shift is difference between 1970-Jan-01 & 1601-Jan-01
         * in 100-nanosecond intervals */
-        const uint64_t c1 = 27111902UL;
-        const uint64_t c2 = 3577643008UL; // issues warning without 'UL'
-        const uint64_t shift = (c1 << 32) + c2;
+        const uint64_t shift = 116444736000000000ULL; // (27111902 << 32) + 3577643008

         union {
             FileTimeT as_file_time;

Windows FileTime 与 UNIX 时间有不同的偏移量,之前在 Boost 中的代码在某些优化编译器中不会生成正确的偏移量差异。

关于c++ - Boost C++ date_time microsec_clock 和 second_clock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1567388/

相关文章:

c++ - 使用自定义安装目录在 Windows 上的 Code::Blocks 中链接 SDL-bgi

c++ - C++ 中的类为什么不是对象?

c++ - 带有 -o3 标志的 g++ 中的链接器命令失败,退出代码为 1

javascript - 日期计算的奇怪错误

javascript - 具有已知偏移量且没有夏令时的已知位置的时间

c++ - 如何在编译时漂亮地打印模板参数的名称

c++ - 在 macOS 10.13.6 clang 7.0 上的 Qt 5.12.0 上找不到“QtSerialPort”文件

python - 如何将日期时间/时间戳从一个时区转换为另一个时区?

c++ - 如何从 boost::spirit::lex 标记确定行/列号?

c++ - 使用 std::max boost ublas 多精度模板解析失败