I am using Howard Hinnant's date C++ library (https://howardhinnant.github.io/date/date.html), but I have some confusions using it. Below is a program where I use this library to print the year-month-day of the 3rd Friday of Nov 2017. The date::year_month_weekday
class, when used with date::sys_days()
, shows a correct date (Nov 17, 2017), but when I convert it to struct tm
with std::chrono::system_clock::to_time_t
, the results stored in this tm
becomes Nov 16, 2017. I tested other cases, it seems struct tm
converted from date::year_month_weekday
always one day behind. Did I miss something in my program? The program is listed as below, C++ 11 is needed to compile it.
#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;
}
The output of this program is as follows
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