The following will by my simple helper, that should behave just like std::chrono::system_clock
but with the epoch being 1.1. 2000, that I can easily cast durations to seconds (or milliseconds or centiseconds) and store them in some records (originated from small devices).
It all started with one constexpr
:
/// 1.1.2000 0:00
static constexpr time_point<system_clock> epoch
= time_point<system_clock>(seconds(946681200))
Which helped me to get e.g. milliseconds from 1.1.2000 like this:
duration_cast<milliseconds>( system_clock::now() - epoch ).count()
The problem is, that there is no contract / specification what is the epoch, but usually is 1.1. 1970.
(I have once selected 1.1. 2000 because of RTCs in units and designed the firmware to work until 1.1. 2100 when I will probably be dead already or very very old man and won't have to care... record size and amount of data transmitted was more important at the time I have designed the protocol.)
(There are some using std::chrono::system_clock
and such inside namespace firda
in that header)
#include "basics.hpp"
using namespace firda;
/// Clock with altered epoch
template<class Clock = system_clock
, typename Clock::rep Epoch = 946681200>
struct adapted_clock {
using rep = typename Clock::rep;
using period = typename Clock::period;
using duration = typename Clock::duration;
using time_point = typename firda::time_point<adapted_clock>;
static constexpr bool is_steady
= Clock::is_steady;
static constexpr typename Clock::time_point epoch
= typename Clock::time_point(seconds(Epoch));
static time_point now() {
return time_point(Clock::now() - epoch);
}
static time_t to_time_t(const time_point& t) {
return Clock::to_time_t(epoch + t.time_since_epoch());
}
static time_point from_time_t(time_t t) {
return time_point(Clock::from_time_t(t) - epoch);
}
};
using y2k_clock = adapted_clock<>;
int main() {
auto now1 = system_clock::now();
auto now2 = y2k_clock::now();
cout << "now1.count: " << duration_cast<seconds>(now1
.time_since_epoch()).count() << '\n';
cout << "now2.count: " << duration_cast<seconds>(now2
.time_since_epoch()).count() << '\n';
time_t time1 = system_clock::to_time_t(now1);
time_t time2 = y2k_clock::to_time_t(now2);
cout << "time1: " << std::ctime(&time1) << '\n';
cout << "time2: " << std::ctime(&time2) << '\n';
}