fmt icon indicating copy to clipboard operation
fmt copied to clipboard

Support strftime `-` extension

Open jayache80 opened this issue 2 years ago • 5 comments

With strftime a single digit 12-hour hour can be formatted to not have a leading zero using %-I. This seems to not be possible with fmt::format.

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

int main() {
    std::cout << "%-I:%M using strftime:" << std::endl;
    std::time_t t_ = std::time(nullptr);
    char mbstr[100];
    if (std::strftime(mbstr, sizeof(mbstr), "%-I:%M", std::localtime(&t_))) {
        std::cout << mbstr << std::endl;
    }

    std::cout << "%-I:%M using fmt::format:" << std::endl;
    const auto t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
    const auto time_str = fmt::format("{:%-I:%M}", fmt::localtime(t));
    // terminate called after throwing an instance of 'fmt::v8::format_error'
    //   what():  invalid format
    std::cout << time_str << std::endl;

    return 0;
}

There are probably more instances where strftime parity is not quite met. It would great if it was, or if any user error could be pointed out :)

jayache80 avatar Jul 03 '22 09:07 jayache80

I don't see %-I documented in https://man7.org/linux/man-pages/man3/strftime.3.html. Is it some kind of an extension?

vitaut avatar Jul 03 '22 13:07 vitaut

On the man page you linked:

Glibc notes Glibc provides some extensions for conversion specifications. (These extensions are not specified in POSIX.1-2001, but a few other systems provide similar features.) Between the '%' character and the conversion specifier character, an optional flag and field width may be specified. (These precede the E or O modifiers, if present.)

   The following flag characters are permitted:

   _      (underscore) Pad a numeric result string with spaces.

   -      (dash) Do not pad a numeric result string

so I'd suppose it is a glibc extension. Does that preclude it?

jayache80 avatar Jul 03 '22 20:07 jayache80

{fmt} supports only standard specifiers at the moment but a PR to add - would be welcome.

vitaut avatar Jul 04 '22 15:07 vitaut

Hi @vitaut I've started working on this but have some questions about differing behavior I'm seeing between platforms (some of tests are failing on Windows only). Does {fmt} have an IRC development channel or something of the sort?

jayache80 avatar Aug 17 '22 06:08 jayache80

There is no IRC, we usually discuss such issues on github.

vitaut avatar Aug 17 '22 17:08 vitaut