700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > c语言获取当前系统日期时间 C语言获取系统当前时间

c语言获取当前系统日期时间 C语言获取系统当前时间

时间:2019-05-13 16:34:27

相关推荐

c语言获取当前系统日期时间 C语言获取系统当前时间

函数名: time ()

头文件:time.h

函数原型:time_t time(time_t * timer)

功 能: 获取当前的系统时间,返回的结果是一个time_t类型,其实就是一个大整数,其值表示从UTC(Coordinated Universal Time)时间1970年1月1日00:00:00(称为UNIX系统的Epoch时间)到当前时刻的秒数。然后可以调用localtime将time_t所表示的UTC时间转换为本地时间(我们是+8区,比UTC多8个小时)并转成struct tm类型,该类型的各数据成员分别表示年月日时分秒。

补充说明:time函数的原型也可以理解为 long time(long *tloc),因为在time.h这个头文件中time_t 实际上就是:

#ifndef _TIME_T_DEFINED

typedef long time_t; /* time value */

#define _TIME_T_DEFINED /* avoid multiple def's of time_t */

#endif

time_t的数字是按UTC算的,跟时区无关,同一个时刻全球所有计算机上的time(NULL)返回值都相同。

用localtime转换成可显示的格式时才需要考虑时区。

实例:

#include #include int main(int argc, char **argv)

{

time_t tmpcal_ptr;

struct tm *tmp_ptr = NULL;

time(&tmpcal_ptr);

//tmpcal_ptr = time(NULL); 两种取值方法均可以

printf("tmpcal_ptr=%d\n", tmpcal_ptr);

tmp_ptr = gmtime(&tmpcal_ptr);

printf("after gmtime, the time is:%d:%d:%d\n", tmp_ptr->tm_hour, tmp_ptr->tm_min, tmp_ptr->tm_sec);

tmp_ptr = localtime(&tmpcal_ptr);

printf ("after localtime, the time is:%d.%d.%d ", (1900+tmp_ptr->tm_year), (1+tmp_ptr->tm_mon), tmp_ptr->tm_mday);

printf("%d:%d:%d\n", tmp_ptr->tm_hour, tmp_ptr->tm_min, tmp_ptr->tm_sec);

return 0;

}

运行结果:

tmpcal_ptr=1470831228

after gmtime, the time is:12:13:48

after localtime, the time is:.8.10 20:13:48

结论:

gmtime转出来的是0时区的标准时间;

localtime是将时区考虑在内了,转出的当前时区的时间。但是注意,有些嵌入式设备上被裁减过的系统,时区没有被设置好,导致二者转出来的时间都是0时区的。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。