C语言获取当前时间

操作系统提供了很多系统调用,既方便程序员编程,又提高了程序的可移植性。在介绍利用系统调用获取当前时间之前,先辨析几个基本的概念。

API ,系统调用 ,封装例程

  • API只是一个函数定义。
  • 系统调用通过软中断向内核发出一个明确的请求。
  • Libc库定义了一些API引用的封装例程,唯一的目的就是发布系统调用。一般每个系统调用对应一个封装例程。
  • API可能提供用户态的服务,如数学函数。一个简单的API可能调用几个系统调用,不同的API也可能调用了同一个系统调用。 C库对time_t, tm的定义

time.h中time_t, tm的定义

  • time_t 其实就是long数据类型。
  • tm是一个结构体。主要的成员变量是年(相对于1900年的差值),月,日,时,分,秒。

time.h中函数介绍

time_t(time_t *timer);

  • Parameter: timer

  • Return Value: Return the time as seconds elapsed since midnight, January 1, 1970, or -1 in the case of an error.

struct tm *localtime( const time_t *timer );

  • Return Value: localtime returns a pointer to the structure result. If the value in timer represents a date before midnight, January 1, 1970, localtime returns NULL.
  • Parameter: timer Pointer to stored time


获取时间代码示例

#include <stdio.h>
 #include <time.h>
 int 
 main(void)
 {
     time_t tt;
     struct tm *t;
     tt = time(NULL);
     t = localtime(&tt);
     printf("time:%d:%d:%d:%d:%d:%d!\n", t->tm_year + 1900, t->tm_mon, t->tm_mday, \
                    t->tm_hour, t->tm_min, t->tm_sec);
         return 0;
 }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值