I have a program I'm writing to take inputs from the command line or a file with the format: 9999.365 --> Fri 31 Dec 9999 Where the output needs to look like the second part of that example. I'm having trouble understanding how to go about taking a string formatted like xxxx.xxx and converting it to a proper time_t object representing a value. Anyone have advice for this?
I've tried looking up how to do so, but my C++ knowledge is not wide and I'm very new to the language so much of what I've found doesn't appear to work or I just don't understand it.
You could simply use the stream parsing utilities in
std::chrono.for
time_twe just then convert:Use:
you could probably make this faster by rolling your own parser, as stream-based C++ isn't all that super fast, but if you aren't doing this on a per-pixel*frame basis (or similar) I wouldn't bother. (Ie, take a string, split it on
., and check there are 2 parts, convert the first to a year, make a time point, add on the day, etc).Adding some
std::moves would be microoptimizations. Moving over to astd::string_viewmight also improve things, but stream-based parsing ofstd::string_viewis C++23.I'd discourage use of
time_tunless you need it for interop with C libraries or the like. C++'sstd::chronotime primitives are far less ancient in design; there are a pile of bugs that are difficult to generate withstd::chronobut are trivial to hit withtime_t.