将double转换为struct tm [英] Convert double to struct tm
问题描述
我有一个 double
包含秒。我想将它转换为 struct tm
。
I have a double
containing seconds. I would like to convert this into a struct tm
.
我找不到一个标准函数, 。我必须手动填写 struct tm
吗?
I can't find a standard function which accomplishes this. Do I have to fill out the struct tm
by hand?
我只是有意转换为 time_t
和 http://www.StackOverflow.com 不会让我发布,除非我链接。
I just accidentally asked this about converting to a time_t
and http://www.StackOverflow.com will not let me post unless I link it.
推荐答案
MSalters回答是正确的,但我想我会添加一些细节。
MSalters answer is correct, but I thought I'd add a bit of detail.
您需要将 double
转换为r值 time_t
,然后使用 localtime
转换为 struct tm
。例如,如果 double foo
是包含秒的变量:
You'll need to cast your double
to an r-value time_t
then use localtime
to convert to a struct tm
. For example if your double foo
is your variable containing seconds:
const time_t temp = foo;
tm* bar = localtime(&temp);
有关 localtime
的回报:
结构可以在
std :: gmtime
,std :: localtime
和std :: ctime
,并且可能会在每次调用时覆盖。
The structure may be shared between
std::gmtime
,std::localtime
, andstd::ctime
, and may be overwritten on each invocation.
意味着对这些函数的任何调用可能会覆盖 bar
中的值。一个更好的选择是复制 localtime
的返回:
Meaning subsequent calls to any of these functions may overwrite the value in bar
. A preferable option would be copying localtime
's return:
const time_t temp = foo;
tm bar = *localtime(&temp);
另一个参考点是你不能 code> localtime(dynamic_cast< const time_t *>(& foo)) 或 ,因为 localtime((const time_t *)& foo)
foo
是 double
和 time_t
是一个整数值。该值需要隐式转换。只需输入 double *
即可产生 nullptr
。
One more point of reference is that you cannot simply or localtime(dynamic_cast<const time_t*>(&foo))
because localtime((const time_t*)&foo)
foo
is a double
and time_t
is an integral value. The value needs to be implicitly converted. Simply casting the double*
results in a nullptr
.
这篇关于将double转换为struct tm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!