【发布时间】:2017-03-25 15:08:32
【问题描述】:
我正在使用 Howard Hinnant 的 date C++ 库 (https://howardhinnant.github.io/date/date.html),但我在使用它时有些困惑。下面是一个程序,我使用这个库打印 2017 年 11 月的第三个星期五的年月日。date::year_month_weekday 类与 date::sys_days() 一起使用时,显示正确的日期(2017 年 11 月 17 日),但是当我使用std::chrono::system_clock::to_time_t 将其转换为struct tm 时,存储在此tm 中的结果变为2017 年11 月16 日。我测试了其他情况,似乎struct tm 从date::year_month_weekday 转换为总是落后一天。我错过了我的程序中的某些内容吗?程序如下,编译需要C++ 11。
#include <iostream>
#include <chrono>
#include <sys/time.h>
#include "date.h"
using namespace std;
using namespace std::chrono;
using namespace date;
int main(int argc, char *argv[]) {
date::year y(2017);
date::month m(11);
date::weekday wd((unsigned)5);
date::weekday_indexed wi(wd,3);
date::year_month_weekday dmwd(y, m, wi);
std::cout << date::sys_days(dmwd) << std::endl; //prints 2017-11-17, which is the 3rd Friday of Nov 2017
time_t tt = std::chrono::system_clock::to_time_t(date::sys_days(dmwd));
struct tm tm1;
localtime_r(&tt, &tm1);
std::cout << "tm1.tm_year = " << tm1.tm_year << std::endl;
std::cout << "tm1.tm_mon = " << tm1.tm_mon << std::endl;
std::cout << "tm1.tm_mday = " << tm1.tm_mday << std::endl; //prints 16 instead of 17, one day behind. tm.mday is from 1 to 31.
return 0;
}
这个程序的输出如下
2017-11-17
tm1.tm_year = 117 <-- 117+1900=2017
tm1.tm_mon = 10 <-- tm_mon starts form 0, so 10 means November
tm1.tm_mday = 16 <-- tm_mday starts from 1, so 16 is the 16-th day in a month
【问题讨论】:
-
你试过用
gmtime_r()代替localtime_r()吗? -
是的,我刚试过,
gmtime_r确实给出了一致的结果,谢谢提示。由于date::year_month_weekday不包含时间(小时和分钟)信息,我想知道日期库在转换为struct tm时如何处理它。我还打印了从date::year_month_weekday转换而来的struct tm的tm_hour和tm_min。对于所有情况,似乎tm_hour == 18和tm_min == 0- 可能是因为我在 UTC-6 时区? -
Fwiw,这里是创建
dmwd的替代语法:auto dmwd = fri[3]/nov/2017;