Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enumerate each hours of a day

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;
}
like image 882
Daniel Anderson Avatar asked Sep 18 '25 11:09

Daniel Anderson


1 Answers

The following:

#include <chrono>
#include <iostream>

using namespace std::chrono;

constexpr const char* zoneName = "Europe/Berlin";

void PrintHours(year_month_day day) {
    // get the year-month-day 00:00:00 in the specific timezone.
    for (auto it = zoned_time(zoneName, local_days(day));
         // Get the day in the iterator and compare with starting day.
         year_month_day(floor<days>(it.get_local_time())).day() == day.day();
         // Increment the day in one hour and come back to the timezone.
         it = it.get_sys_time() + hours(1)) {
        std::cout << it << '\n';
    }
}
int main(int argc, char** argv) {
    PrintHours(year_month_day{year(2023), month(10), day(29)});
    return 1;
}

Outputs:

2023-10-29 00:00:00 CEST
2023-10-29 01:00:00 CEST
2023-10-29 02:00:00 CEST
2023-10-29 02:00:00 CET
2023-10-29 03:00:00 CET
2023-10-29 04:00:00 CET
2023-10-29 05:00:00 CET
2023-10-29 06:00:00 CET
2023-10-29 07:00:00 CET
2023-10-29 08:00:00 CET
2023-10-29 09:00:00 CET
2023-10-29 10:00:00 CET
2023-10-29 11:00:00 CET
2023-10-29 12:00:00 CET
2023-10-29 13:00:00 CET
2023-10-29 14:00:00 CET
2023-10-29 15:00:00 CET
2023-10-29 16:00:00 CET
2023-10-29 17:00:00 CET
2023-10-29 18:00:00 CET
2023-10-29 19:00:00 CET
2023-10-29 20:00:00 CET
2023-10-29 21:00:00 CET
2023-10-29 22:00:00 CET
2023-10-29 23:00:00 CET
like image 65
KamilCuk Avatar answered Sep 21 '25 01:09

KamilCuk