以前实际上用过,很想对C语言中的时间函数了解多一点,趁着这个寒假,查了些资料,大概把我现在能用到的关于时间的操作在此记录下来。
通过几个函数来熟悉C语言中对时间的操作。
(注:以下程序均在VS2010上编译通过。)
①time()函数。
可以通过time()函数来获得日历时间。其原型为:
time_t time(time_t *timer);
一般参数为空,返回值类型time_t是一个长整型数,函数将返回现在的日历时间,即从一个时间点(所有不同版本的Visual C++都是从1970年1月1日0时0分0秒)到现在的经过的秒数。
例子程序:
#include<stdio.h>
#include<time.h>
void main()
{
time_t lt;
lt=time(NULL);
printf("1970年1月1日0时0分0秒到现在经历了%ld秒\n",lt);
}
运行结果(结果与程序运行的时间有关,贴出我此时运行出的结果):
③使用C库函数来显示日期和时间。
首先要介绍一下C语言中的一个日期的结构体类型,tm类型。其在time.h中的定义如下:
#ifndef _TM_DEFINED
struct tm {
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
};
#define _TM_DEFINED
#endif
然后可以介绍有关的函数了。time.h提供了两种不同的函数将日历时间(一个长整型数)转换成我们平时看到的把年月日时分秒分开的时间格式:
struct tm *gmtime(const time_t *timer);
struct tm *localtime(const time_t *timer);
其中gmtime()函数是将日历时间转换为世界标准时间(即格林尼治时间),并返回一个tm结构体来保存这个时间,而localtime()函数是将日历时间转换为本地时间(在中国地区获得的本地时间会比世界标准时间晚8个小时)。
例子程序:
#include<stdio.h>
#include<time.h>
void main()
{
struct tm *local;
time_t t;
t=time(NULL);
local=localtime(&t);
printf("现在北京时间是%d点\n",local->tm_hour);
local=gmtime(&t);
printf("世界标准时间是%d点\n",local->tm_hour);
}
运行结果(运行结果与运行的时间有关,我是在早上9点多钟运行这个程序的):
现在北京时间是9点
世界标准时间是1点
请按任意键继续. . .
这样子我们就可以完全才输出此刻的年月日时分秒了,当然需要逐个来输出。其实C库函数还提供了一个很有用的以固定的时间格式来输出年月日时分秒的函数。这两个函数原型如下:
char *asctime(const struct tm *timeptr);
char *ctime(const time_t *timer);
asctime()函数是通过tm结构来生成具有固定格式的保存时间信息的字符串,而ctime()是通过日历时间来生成时间字符串。
这样下面的例子程序就容易理解了:
#include<stdio.h>
#include<time.h>
void main()
{
struct tm *local;
time_t t;
t=time(NULL);
local=localtime(&t);
printf(asctime(local));
local=gmtime(&t);
printf(asctime(local));
printf(ctime(&t));
}
运行结果(我是在早上9点多运行这个程序的):
Fri Jan 20 09:55:56 2012
Fri Jan 20 01:55:56 2012
Fri Jan 20 09:55:56 2012
请按任意键继续. . .
C语言还可以以我们规定的各种形式来规定输出时间的格式。要用到时可以查阅相关的资料,限于篇幅,就介绍到这里。
④这里介绍计算持续的时间长度的函数。之前已经介绍了使用clock()函数的例子,它可以精确到毫秒级。其实我们也可以使用difftime()函数,但它只精确到秒。该函数的定义如下:
double difftime(time_t time1,time_t time0);
例子程序:
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
void main()
{
time_t start,end;
start=time(NULL);
for(int i=0;i<1000000000;i++);
end=time(NULL);
printf("这个循-环用了%f秒\n",difftime(end,start));
}
运行结果:
这个循环用了3.000000秒
请按任意键继续. . .
⑤最后介绍mktime()函数。原型如下:
time_t mktime(struct tm *timer);
可以使用函数将用tm结构表示的时间转换为日历时间。其返回值就是转换后的日历时间。这样我们就可以先制定一个分解时间,然后对这个时间进行操作。下面的例子用来计算2012年1月20日是星期几:
#include<time.h>
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
struct tm t;
time_t t_of_day;
t.tm_year=2012-1900;
t.tm_mon=0;
t.tm_mday=20;
t.tm_hour=0;
t.tm_min=12;
t.tm_sec=1;
t.tm_isdst=1;
t_of_day=mktime(&t);
printf(ctime(&t_of_day));
return 0;
}
运行结果:
Fri Jan 20 00:12:01 2012
请按任意键继续. . .