Search code examples
c++c++-chrono

C++ structure for time with TZ, but without date?


Are there any structures in the C++ std::chrono spec to represent a time, along with a time zone, but without the date? The issue is that I want to be able to filter records which have unix time (time_t), and return all records which have times between "10:00 EST" and "11:00 EST". This would require converting the time_t to EST, stripping the time, and then comparing it to a "time" structure.


Solution

  • C++20 introduces time zone support for chrono. It isn't shipping yet, but there's a free, open-source preview library. It does require some installation for the time zone support.

    There is no ready made data-structure for {time-of-day, time_zone}. However you could easily build your own by storing time-of-day as a chrono::duration (say seconds?) and a chrono::time_zone const* (date::time_zone const* in the preview lib).

    #include "date/tz.h"
    #include <chrono>
    #include <ctime>
    #include <iostream>
    
    struct my_event
    {
        date::time_zone const* tz;
        std::chrono::seconds tod;
    };
    
    std::ostream&
    operator<<(std::ostream& os, const my_event& e)
    {
        return os << date::format("%T ", e.tod) << e.tz->name();
    }
    
    int
    main()
    {
        using namespace date;
        using namespace std;
        using namespace std::chrono;
    
        time_t t = 1609186734;
        zoned_time zt{"America/New_York", sys_seconds{seconds{t}}};
        auto local_time = zt.get_local_time();
        auto tz = zt.get_time_zone();
        my_event e{tz, local_time - floor<days>(local_time)};
        cout << e << '\n';
    }
    

    Output:

    15:18:54 America/New_York