所有的unix系统都使用同一个时间和日期的起点:格林尼治时间(GMT)1970年1月1日午夜0点
时间通过一个预定义的类型time_t来处理,在linux系统中,它是一个长整型。包含在time.h中。
#include<time.h>
time_t time(time_t *tloc);
通过time函数可以得到底层的时间值,它返回的是从纪元开始至今的秒数。如果tloc不是一个空指针,time函数还会把返回值写入到tloc指针指向的位置。
#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
int i;
time_t the_time;
for(i = 1; i <= 10; i++) {
the_time = time((time_t *)0);
printf("The time is %ld\n", the_time);
sleep(2);
}
exit(0);
}
#include<time.h>
double difftime(time_t time1,time_t time2);
difftime函数是计算两个时间值之间的差,并将time1-time2的值作为浮点数返回。
为了提供更有意义的时间和日期,你需要把时间值转换为可读的时间和日期,有一些标准函数可以做到这些。
#include<time.h>
struct tm *gmtime(const time_t timeval);
tm结构被定义为下面所示的成员
int tm_sec; /* Seconds. [0-60] (1 leap second) */
int tm_min; /* Minutes. [0-59] */
int tm_hour; /* Hours. [0-23] */
int tm_mday; /* Day. [1-31] */
int tm_mon; /* Month. [0-11] */
int tm_year; /* Year - 1900. */
int tm_wday; /* Day of week. [0-6] */
int tm_yday; /* Days in year.[0-365] */
int tm_isdst; /* 是否夏令时*/
下面这个gmtime.c利用tm结构gmtime打印当前的时间和日期
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
struct tm *tm_ptr;
time_t the_time;
(void) time(&the_time);
tm_ptr = gmtime(&the_time);
printf("Raw time is %ld\n", the_time);
printf("gmtime gives:\n");
printf("date: %02d/%02d/%02d\n",
tm_ptr->tm_year, tm_ptr->tm_mon+1, tm_ptr->tm_mday);
printf("time: %02d:%02d:%02d\n",
tm_ptr->tm_hour, tm_ptr->tm_min, tm_ptr->tm_sec);
exit(0);
}
#include<time.h>
struct tm *localtime(const time_t *timaval);
要把已分解出来的tm结构再转换为原始的time_t时间值,你可以使用mktime函数:
#include<time.h>
time_t mktime(struct tm *timeptr);
如果结构tm结构不能表示time_t的值,mktime但会-1
为了得到更友好的时间和日期,像date命令输出那样。你可以使用asctime函数和ctime函数。
#include<time.h>
char *asctime(const struct tm *timeptr);
char *ctime(struct time_t *timeval);
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
time_t timeval;
(void)time(&timeval);
printf("The date is: %s", ctime(&timeval));
exit(0);
}