【问题标题】:epoch in C++ using mktime使用 mktime 在 C++ 中的纪元
【发布时间】:2017-08-02 03:16:08
【问题描述】:

我正在阅读以下内容:http://en.cppreference.com/w/cpp/chrono/c/mktime

其中特别说明:

将本地日历时间转换为自纪元以来的时间作为 time_t 对象。

我假设这个纪元是 unix 纪元(1970 01 01),但来自以下程序

#include <ctime>
#include <iostream>

int main()
{
    std::tm example = {00, 00, 00, 01, 12, 69};
    std::cout << std::mktime(&example) << std::endl;
    return 0;
}

我得到了输出

0

这告诉我纪元是 1969 年 12 月 1 日的 00:00:00。 是否定义了 epoch 实现,还是我有其他一些基本的误解?

【问题讨论】:

  • epoch 不是由C++ 标准定义的。 POSIX 将其定义为 1970 01 01 所以 unix/linux 机器符合它。
  • 我在 unix 机器上运行了这个

标签: c++ date datetime


【解决方案1】:

对于一种现代的、不易出错的方法,这里有一个 free, open-source C++11/14/17 library 来做同样的事情,避免容易出错、线程不安全的 C API。

#include "chrono_io.h"
#include "date.h"
#include <iostream>

int
main()
{
    using namespace date;
    sys_seconds t = sys_days{1_d/dec/1969};
    std::cout << t.time_since_epoch() << '\n';
}

输出:

-2678400s

【讨论】:

    【解决方案2】:

    See here.

    tm_mon 定义为自 1 月 [0,11] 以来的月份,这使得您的 12 个月给 std::tm 到 12 月 + 1 个月,因此是 1970 年 1 月。

    例如,24 个月的 1968 年也返回 0:

    #include <ctime>
    #include <iostream>
    
    int main(){
      std::tm example;
      example.tm_sec = 0;
      example.tm_min = 0;
      example.tm_hour = 0;
      example.tm_year = 68;
      example.tm_mon = 24;
      example.tm_mday = 1;
    
      std::cout << std::mktime(&example) << "\n";
      return 0;
    }
    

    输出:

    0
    

    (或 -3600 因为夏令时)

    【讨论】:

      猜你喜欢
      • 2018-01-09
      • 1970-01-01
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 2014-12-31
      • 2010-10-28
      • 2013-06-22
      • 2015-10-07
      相关资源
      最近更新 更多