HowardHinnant / date

A date and time library based on the C++11/14/17 <chrono> header
Other
3.14k stars 677 forks source link

Format specified for parsing duration strings like 20s, 5ms etc. #761

Closed wAuner closed 1 year ago

wAuner commented 1 year ago

Is it possible to parse strings like "20ms", "5ms", "1h" etc. to chrono::durations? I was looking at from_stream and parse, but I wasn't able to find a promising format specifier. Thanks.

HowardHinnant commented 1 year ago

There's no parse flags to help with this one.

If you know the units you are parsing, it isn't difficult to parse the pieces with something like:

    istringstream in{"20ms"};
    string units;
    int mi;
    in >> mi >> units;
    milliseconds d{mi};
    assert(units == "ms");

If you don't know the units ahead of time, you could parse into nanoseconds and switch on the units among a small set of assumed units:

    istringstream in{"20ms"};
    string units;
    int i;
    in >> i >> units;
    nanoseconds d;
    if (units == "ms")
        d = milliseconds{i};
    else if (units == "h")
        d = hours{i};
    else
        cerr << "parse error\n";
wAuner commented 1 year ago

Thank you Howard. Now that I see the examples, it really is simple. Thanks for your good work.