C语言 time_t 是什么原始数据类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2792551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:23:55  来源:igfitidea点击:

What primitive data type is time_t?

ctypesprintftime-t

提问by

I do not know the data type of time_t. Is it a float double or something else? Because if I want to display it I need the tag that corresponds with it for printf. I can handle the rest from there for displaying time_tbut I need to know the data type that corresponds with it.

我不知道time_t. 它是 float double 还是其他什么?因为如果我想显示它,我需要与它对应的标签printf。我可以从那里处理其余的用于显示,time_t但我需要知道与之对应的数据类型。

采纳答案by Matthew Flaschen

Unfortunately, it's not completely portable. It's usually integral, but it can beany "integer or real-floating type".

不幸的是,它并不完全便携。它通常是整数,但它可以是任何“整数或实数浮点型”。

回答by dan04

It's platform-specific. But you can cast it to a known type.

它是特定于平台的。但是您可以将其转换为已知类型。

printf("%lld\n", (long long) time(NULL));

回答by user2483388

You can use the function difftime. It returns the difference between two given time_tvalues, the output value is double(see difftime documentation).

您可以使用该功能difftime。它返回两个给定time_t值之间的差值,输出值为double(参见difftime 文档)。

time_t actual_time;
double actual_time_sec;
actual_time = time(0);
actual_time_sec = difftime(actual_time,0); 
printf("%g",actual_time_sec);

回答by Sniggerfardimungus

You could always use something like mktime to create a known time (midnight, last night) and use difftime to get a double-precision time difference between the two. For a platform-independant solution, unless you go digging into the details of your libraries, you're not going to do much better than that. According to the C spec, the definition of time_t is implementation-defined (meaning that each implementation of the library can define it however they like, as long as library functions with use it behave according to the spec.)

您始终可以使用 mktime 之类的东西来创建已知时间(午夜、昨晚),并使用 difftime 来获得两者之间的双精度时差。对于独立于平台的解决方案,除非您深入研究库的详细信息,否则您不会做得更好。根据 C 规范, time_t 的定义是实现定义的(意味着库的每个实现都可以定义它,只要他们喜欢,只要使用它的库函数按照规范运行。)

That being said, the size of time_t on my linux machine is 8 bytes, which suggests a long int or a double. So I did:

话虽如此,我的 linux 机器上 time_t 的大小是 8 个字节,这表明是 long int 或 double。所以我做了:

int main()
{
    for(;;)
    {
        printf ("%ld\n", time(NULL));
        printf ("%f\n", time(NULL));
        sleep(1);
    }
    return 0;
}

The time given by the %ld increased by one each step and the float printed 0.000 each time. If you're hell-bent on using printf to display time_ts, your best bet is to try your own such experiment and see how it work out on your platform and with your compiler.

%ld 给出的时间每一步增加 1,浮点数每次打印 0.000。如果您一心想要使用 printf 来显示 time_ts,那么最好的办法是尝试自己的此类实验,看看它在您的平台和编译器上如何运行。