I came up with the following function to obtain epoch seconds that correspond to previous midnight in a local time zone:
#include <iostream>
#include <chrono>
#include <date/date.h>
#include <date/tz.h>
long local_midnight_epoch() {
using namespace date;
using namespace std::chrono;
auto t = std::chrono::system_clock::now();
auto* zone = date::current_zone();
auto zt = make_zoned(zone, t);
zt = floor<days>(zt.get_local_time());
auto seconds_since_midnight = floor<seconds>(t - zt.get_sys_time());
std::chrono::time_point<std::chrono::system_clock> ts = std::chrono::system_clock::now();
auto epoch = std::chrono::duration_cast<std::chrono::seconds>(ts.time_since_epoch());
epoch -= seconds_since_midnight;
return epoch.count();
}
int main(void) {
std::cerr << local_midnight_epoch() << std::endl;
}
The code uses Howard Hinnant's date library. It first computes seconds passed since midnight in a local time zone, and then subtract that the current epoch. Is there an easier way to accomplish this? Thanks.