I want to get each hours of a day, local time. For places without daylight saving time it is easy, but when there DST start or ends, current days have 23 or 25 hours!
I wrote this code to properly get it, but I’m wondering if there is a simpler way with chrono to write the function PrintHours()
#include <iostream>
#include <chrono>
using namespace std::chrono;
constexpr const char* zoneName = "Europe/Berlin";
void PrintHours(std::chrono::local_days date)
{
zoned_time utcTime{"UTC", zoned_time{zoneName, date}};
auto localTime = zoned_time{zoneName, utcTime};
auto dp = std::chrono::floor<days>(localTime.get_local_time());
// keep looping until day change!
for (auto startingDay = year_month_day{dp}.day(); startingDay == year_month_day{dp}.day(); dp = std::chrono::floor<days>(localTime.get_local_time()))
{
std::cout << zoneName << localTime<< " UTC: " << utcTime << std::endl;
// bump time to next hour
utcTime = zoned_time("UTC", utcTime.get_local_time() + hours(1));
localTime= zoned_time{zoneName, utcTime};
}
}
int main(int argc, char **argv)
{
using namespace std::chrono;
year_month_day ymd{year(2023), month(10), day(29)};
PrintHours(local_days(ymd));
return 1;
}