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 实际上就是:

<span style="font-family:Arial;font-size:12px;">#ifndef _TIME_T_DEFINED
typedef  long  time_t;             /* time value */
#define _TIME_T_DEFINED           /* avoid multiple def's of time_t */
#endif </span>

       time_t的数字是按UTC算的,跟时区无关,同一个时刻全球所有计算机上的time(NULL)返回值都相同。
用localtime转换成可显示的格式时才需要考虑时区。

实例:

#include <time.h>
#include <stdio.h>


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:2016.8.10 20:13:48

结论:

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


  • 13
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值