Search code examples
c++c++-chrono

To identify ambigious local time using std::chrono


How to identify the given epoch time converted to local time(time zone UTC-8) is a ambigious ?

Example. Epoch time 1699173796 when converted to local time(time zone UTC-8) gives November 5, 2023 1:43:16 AM and for the same local time one more epoch time also available 1699177396.

How to identify this time ambiguity using std::chrono or using any other c++ libraries.

And once find it is a ambigious time, how to select the earliest/latest time for that

I gone through the std::chrono libraries not able to find any APIs


Solution

  • First convert your sys_time into a local time:

    using namespace std::chrono;
    
    auto zone = locate_zone("America/Los_Angeles");
    sys_seconds tp(1699173796s);
    auto local = zone->to_local(tp);
    

    And then convert it back:

    auto earlier = zone->to_sys(local, choose::earliest);
    auto later = zone->to_sys(local, choose::latest);
    

    It's ambiguous iff earlier != later.

    To just tell if a local time is ambiguous, you can also use zone->get_info(local).result == local_info::ambiguous.


    You can also do this with the higher-level zoned_time API instead, which has the benefit of not leaving a local_time floating around with no associated timezone:

    zoned_time original("America/Los_Angeles", sys_seconds(1699173796s));
    zoned_time earlier(original.get_time_zone(), original.get_local_time(), choose::earliest);
    zoned_time later(original.get_time_zone(), original.get_local_time(), choose::latest);