获取c++中自epoch以来的天数(跨平台)

Get number of days since epoch in C++ (cross platform)

本文关键字:跨平台 c++ 中自 epoch 获取      更新时间:2023-10-16

如何在c++中获得自epoch以来的天数计数,我知道我应该使用mktime函数,但我不明白如何实现它

谢谢!

修改cplusplus.com的一些示例代码:

#include <stdio.h>
#include <time.h>
int main ()
{
  time_t seconds;
  seconds = time (NULL);
  int daysSinceEpoch = seconds/(60*60*24);
  printf ("%ld days since January 1, 1970", daysSinceEpoch);
  return 0;
}

日期不容易正确处理。目前的标准库不提供正确执行此操作的能力。您应该使用合适的日期库,例如boost::date或Howard Hinnant的<date>

使用Hinnant的库,代码可能看起来像这样:
date epoch = year(1970)/jan/day(1); // Assuming you're referring to the traditional Unix epoch (some systems such as Cocoa on OS X use the first day of the millenium, Jan 1, 2001 as their epoch)
days d = date::today() - epoch;

通过time(NULL)获取当前时间。将该值传递给gmtime,它将返回一个tm*。阅读tm的文档