I would like to print or extract year/month/day values.
I don\'t want to use time_t
because of the year 2038 problem, but all examples I found on the In
I have used Howard Hinnant's date library to write a function that converts from time_point
to struct tm
:
template
std::tm to_calendar_time(std::chrono::time_point tp)
{
using namespace date;
auto date = floor(tp);
auto ymd = year_month_day(date);
auto weekday = year_month_weekday(date).weekday_indexed().weekday();
auto tod = make_time(tp - date);
days daysSinceJan1 = date - sys_days(ymd.year()/1/1);
std::tm result;
std::memset(&result, 0, sizeof(result));
result.tm_sec = tod.seconds().count();
result.tm_min = tod.minutes().count();
result.tm_hour = tod.hours().count();
result.tm_mday = unsigned(ymd.day());
result.tm_mon = unsigned(ymd.month()) - 1u; // Zero-based!
result.tm_year = int(ymd.year()) - 1900;
result.tm_wday = unsigned(weekday);
result.tm_yday = daysSinceJan1.count();
result.tm_isdst = -1; // Information not available
return result;
}
This effectively bypasses time_t
with its lurking Y2038 problem on 32-bit systems. This function has been contributed to this GitHub wiki, where I hope others will contribute other useful examples and recipes.