当前位置: 技术问答>linux和unix
Linux 时间编程的问题
来源: 互联网 发布时间:2016-09-28
本文导语: #include #include int main(void) { struct tm *local; struct tm *utc; time_t t; time(&t); local=localtime(&t); printf("Local time is %d:%d:%dn",local->tm_hour,local->tm_min,local->tm_sec); utc=gmtime(&t); ...
#include
#include
int main(void)
{
struct tm *local;
struct tm *utc;
time_t t;
time(&t);
local=localtime(&t);
printf("Local time is %d:%d:%dn",local->tm_hour,local->tm_min,local->tm_sec);
utc=gmtime(&t);
printf("UTC is %d:%d:%dn",utc->tm_hour,utc->tm_min,utc->tm_sec);
printf("%s",asctime(local));
printf("%s",asctime(utc));
printf("%s",ctime(&t));
return 0;
}
程序如上:
输出结果:
Local time is 21:9:19
UTC is 13:9:19
Wed Sep 15 13:09:19 2010
Wed Sep 15 13:09:19 2010
Wed Sep 15 21:09:19 2010
----------------------------------------------------
不明白,这2句怎么打印结果是一样的?
printf("%s",asctime(local));
printf("%s",asctime(utc));
为啥第一句打印的不是本地时间而是格林威治时间
|
localtime和gmtime返回的是静态变量的地址,是同一个地址。
可以用localtime_r或者保存到变量里
可以用localtime_r或者保存到变量里
#include
#include
int main(void)
{
struct tm local;
struct tm utc;
time_t t;
time(&t);
local = *localtime(&t);
printf("Local time is %d:%d:%dn",local.tm_hour,local.tm_min,local.tm_sec);
utc = *gmtime(&t);
printf("UTC is %d:%d:%dn",utc.tm_hour,utc.tm_min,utc.tm_sec);
printf("%s",asctime(&local));
printf("%s",asctime(&utc));
printf("%s",ctime(&t));
return 0;
}
|
另外建议用strftime,可以更直观地控制显示
printf("Local time is %d:%d:%dn",local.tm_hour,local.tm_min,local.tm_sec);
===>
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &local);
printf("%sn", buf);
printf("Local time is %d:%d:%dn",local.tm_hour,local.tm_min,local.tm_sec);
===>
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &local);
printf("%sn", buf);