How about a date class that stores an internal std::tm
datetime object and the total seconds since (or before) Jan 1, 1970 as a time_t
. The members of tm
are all int
s and time_t
should be 64bit everywhere (I hope), so in theory that should cover all the times you could consider.
In the constructor of your class you'd need to compute those total seconds and the only standard library function that seems to do that is mktime
. Unfortunately this one only works for dates after Jan 1, 1970.
One possible workaround... add a really big number to the year and work with that internally.
#include <ctime>
#include <iostream>
class CustomDateTime {
const int MKTIME_DELTA = 100000;
std::tm _datetime;
std::time_t _total_seconds;
public:
CustomDateTime(int year, int mon, int day, int hour, int min, int sec) {
_datetime.tm_year = year - 1900 + MKTIME_DELTA;
_datetime.tm_mon = mon - 1;
// copy day, hour, min, sec
_total_seconds = std::mktime(&_datetime);
}
bool operator==(const CustomDateTime& rhs) {
return _total_seconds == rhs._total_seconds;
}
void print() {
std::cout << _datetime.tm_year + 1900 - MKTIME_DELTA << ':'
<< _datetime.tm_mon + 1 << _datetime.tm_mday << '\n';
}
};
That should cover all years between 1970 - MKTIME_DELTA = -98030
and the far far future.