What I would like to do with my simple program is to calculate a difference in seconds between two dates.
time_t referenceDate;
time_t dateNow = time(0);
struct tm referenceDateComponent = {0};
referenceDateComponent.tm_hour = 0;
referenceDateComponent.tm_min = 0;
referenceDateComponent.tm_sec = 0;
referenceDateComponent.tm_year = 89;
referenceDateComponent.tm_mon = 11;
referenceDateComponent.tm_mday = 31;
referenceDate = mktime(&referenceDateComponent);
long seconds = difftime(dateNow, referenceDate);
Whit the code above the application works fine, but if try to set tm.year
negative (to build a date before 1900) the mktime()
function return -1
I know that time_t
type manage only dates starting from Jan 1, 1970 UTC according with the documentation:
For historical reasons, it is generally implemented as an integral value representing the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC (i.e., a unix timestamp). Although libraries may implement this type using alternative time representations.
I know there are also the Boost
libraries but is not a usable solution for me.
So my question would be, there is any way to get difference in seconds from dates starting before 1970?
I recommend using the C++11 std::chrono
namespace and <chrono>
standard headers and the standard functions and classes inside them.
You might also consider difftime from the C standard and localtime & mktime
And there are a lot of good other reasons to upgrade to C++11 at least (or C++14 if you can). Several good recent free software compilers GCC and Clang/LLVM support that standard (compile with -std=c++11
or -std=gnu++14
if you want GNU extensions & C++14)
BTW, your question is much more complex than you believe. Calendars has changed. Julian/Gregorian calendar transition happened in the XXth century in Russia. My late mother was born in 1919, during emigration and the civil war, in a Russian village whose legal system was disputed at that time (Russian revolution did not occur instantly). She had some papers mentioning 13th december 1919, and other papers mentioning 26th december 1919, referring to the same date in two different calendars. How would your software deal with that? I'm not even sure that timezone is enough!
BTW, I'm not sure that Boost or C++11 <chrono>
can reliably deal with such calendar issues.
nwp mentioned in a comment a very good computerphile video: Problem with Time & Timezones.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With