Linux下的时间表示

 在Linux/UNIX系统中时间定义分为两种:一种为系统时间,该时间一般是一个长整型数据,单位为秒。另一种是日历时间。相对于系统时间,日历时间更贴近于人们熟悉的时间表示法,其通过一个tm结构体来更贴切地标明时间的年、月、日、时、分、秒、星期。

 

一.系统时间

是至1970年1月1日到现在所经过的秒数,这个值的数据类型为time_t,是一个长整型数据。time函数获取系统时间。difftime计算两个time_t类型的时间之差的秒数。

示例:time_b.c

 

#include <stdio.h> #include <stdlib.h> #include <time.h> int main( void ){ time_t cur_time1,cur_time2; double a; if ((cur_time1 = time (NULL)) == -1 ){ perror ("time"); exit (1); } printf ("the current time is : %d /n", cur_time1); sleep(5); if ((cur_time2 = time (NULL)) == -1 ){ perror ("time"); exit (1); } printf ("the current time is : %d /n", cur_time2); a=difftime(cur_time2,cur_time1); printf("the different time is :%f/n",a); exit(0); } [root@localhost yuan]# gcc -o time_b time_b.c [root@localhost yuan]# ./time_b the current time is : 1248319633 the current time is : 1248319638 the different time is :5.000000

更精确的时间表示:gettimeofday

与gettimeofday相关的宏

//判断tvp结构体是否被填充

#define timerisset(tvp)

//将tvp指向的结构体置0

#define timerclear(tvp)

//执行result=a+b

#define timeradd(tvp)

//执行result=a-b

#define timersub(tvp)

//比较两个结构体中的值

#define timercmp(tvp)

 

二.日历时间

struct tm

 

把系统时间转换成日历时间

struct tm *gmtime(const time_t *calptr);

struct tm *localtime(const time_t *calptr);

 

把日历时间转换成系统时间

time_t mktime(struct tm *tmptr);

 

把日历和系统时间转换成字符串的形式

char *asctime(const struct tm *tmptr);

char *ctime(const time_t *calptr);

 

strftime给出了对时间更灵活的输出



 

你可能感兴趣的:(linux,struct,gcc,null,日历)