I have a double
containing seconds. I would like to convert this into a time_t
.
I can't find a standard function which accomplishes this. Do I have to fill out the time_t
by hand?
I have a double
containing seconds. I would like to convert this into a time_t
.
I can't find a standard function which accomplishes this. Do I have to fill out the time_t
by hand?
The type of
std::time_t
is unspecified.So, just a safe casting between them could be fine. Also be carefull about portability (because it's type is not specified in the standard) and consider about the values than can not fit while casting from double to integrals.
Chrono Library
As pointed out in deepmax's answer the type of
time_t
is implementation defined. Therefore a cast is not guaranteed to succeed. Thankfully the chrono library has significantly improved the capabilities of time operations.Code Example
To demonstrate how this can be done, I have put a Live Example on ideone.
Explanation
As an example of the improved capabilities provided by the chrono library, a double containing seconds can be used to directly construct a
chrono::duration<double>
.From there,
to_time_t
can be used on achrono::system_clock::time_point
so it's just a matter of constructing ourchrono::system_clock::time_point
with ourchrono::duration<double>
.So given a number of seconds in
double input
we can accomplish an implementation independent conversion like this:Simplification
Although we can get this
time_t
(or achrono::system_clock::time_point
), this is traditionally considered the number of seconds since 00:00:00 in Coordinated Universal Time. Thus, storing the result of "a velocity equation" in atime_t
may be confusing for a traditionalist.The readability of your code would be improved if rather than converting to a
time_t
you simply stopped at converting to achrono::duration<double>
therefore I suggest you go no further than: