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;
 }

猜你喜欢

转载自blog.csdn.net/qq_34302921/article/details/79671051