Convert double to time_t

2020-07-10 03:10发布

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?

2条回答
你好瞎i
2楼-- · 2020-07-10 03:24

The type of std::time_t is unspecified.

Although not defined, this is almost always an integral value holding the number of seconds (not counting leap seconds) since 00:00, Jan 1 1970 UTC, corresponding to POSIX time.

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.

查看更多
狗以群分
3楼-- · 2020-07-10 03:46

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 a chrono::system_clock::time_point so it's just a matter of constructing our chrono::system_clock::time_point with our chrono::duration<double>.
So given a number of seconds in double input we can accomplish an implementation independent conversion like this:

chrono::system_clock::to_time_t(chrono::system_clock::time_point(chrono::duration_cast<chrono::seconds>(chrono::duration<double>(input))))

Simplification

Although we can get this time_t (or a chrono::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 a time_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 a chrono::duration<double> therefore I suggest you go no further than:

chrono::duration<double>(input)
查看更多
登录 后发表回答