Thanks to visit codestin.com
Credit goes to github.com

Skip to content

It's possible to get an exception when working with localised times #4350

@musshorn

Description

@musshorn

Environment:
Windows 10 x64
MSVC Version 17.12.4

It;'s possible to pass a std::chrono::local_seconds object to format that has an ambiguous time, so for example ~2am on April 6th 2025 in Sydney daylight savings ends.

Sample Code (note, system running must be on AEDT)

#include <chrono>
#include <cstdlib>
#include <iostream>
#include <fmt/core.h>
#include <fmt/chrono.h>

int main()
{
    const auto& timeZoneDatabase = std::chrono::get_tzdb();
    const auto& currentZone = timeZoneDatabase.current_zone();
    std::cout << currentZone->name() << '\n'; // This needs to be Australia/Sydney

    uint64_t two_in_the_morning = 1743865205; // just after 2am on 2025/4/6 which is a daylight savings changeover point
    auto dur = std::chrono::duration<uint64_t>(two_in_the_morning);
    auto time_point = std::chrono::time_point<std::chrono::system_clock, std::chrono::duration<uint64_t>>(dur);
    auto time_point_as_local_seconds = currentZone->to_local(std::chrono::floor<std::chrono::seconds>(time_point));

    std::string text = fmt::format("{:%Y-%m-%d %H:%M:%S}", time_point_as_local_seconds);
    std::cout << text << '\n';
    return 0;
}

This block here seems to be the cause:

fmt/include/fmt/chrono.h

Lines 575 to 580 in 94ab51c

template <typename Duration,
FMT_ENABLE_IF(detail::has_current_zone<Duration>())>
inline auto localtime(std::chrono::local_time<Duration> time) -> std::tm {
using namespace std::chrono;
using namespace fmt_detail;
return localtime(detail::to_time_t(current_zone()->to_sys<Duration>(time)));

to_sys can throw exceptions in these cases, and needs to be passed std::chrono::choose

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions