How to manipulate dates/datetimes in c++11?

c++, c++11

Solution

You need to initialize all fields from `tm`, start with

std::tm tm = {0,0,0,0,0,0,0,0,0,0,0};

Without this, the other fields (the ones you don't explicitly set afterwards) will contain arbitrary values. The conversion will also normalize values, which mean that if the field `tm_hour` contains 123456789, it will add so many hours to the day you specified. This is how those nonsense-values for `e1` can be explained. If you initialize all fields explicitly, it will allow your example to return meaningful values, although you might need to set more fields like `isdst` to make it correct for all cases.

I have to admit that I haven't used `chrono` so far as I find the required syntax overly verbose and I keep using my own classes to wrap the C-style time functions. That, of course, is not a statement about the quality and power of `<chrono>`, maybe I should start using it :)

Problem

This is embarrassing, but i am having a hard time doing simple manipulation of datetimes. This is the c# version of what i basically try to achive using c++11; ``` DateTime date1=new DateTime(4,5,2012); DateTime date2=new DateTIme(7,8,2013); int day1=date1.Days; TimeSpan ts=d2-d1; int diffDays=ts.Days; ``` What did i try? ``` std::tm tm; tm.tm_year=113; tm.tm_mon=0; tm.tm_wday=0; std::time_t tt=mktime(&tm); std::chrono::system_clock::time_point then = std::chrono::system_clock::from_time_t(tt); std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); auto e1 = std::chrono::duration_cast<std::chrono::hours>(now - then).count(); ``` The value of e1 (379218) makes no sense what so ever. I took a look at chrono, which is presented as the c++11 standard library for datetime but i just could not find an example of how to create a date having int year=2012, int month=2, int day=14. PS:Is chrono sufficient for handling date/times/timezones in c++11? Is there a need for time.h?

Original source