Convert double to time_t

我的未来我决定 提交于 2019-12-04 04:05:27

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.

Jonathan Mee

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!