c语言中有时间函数吗 c语言时间类型( 五 )


time_t localTime1;
time( localTime1 );
newtime=localtime(localTime1);
strftime( tmpbuf, 128, "Today is %A, day %d of %B in the year %Y. ", newtime);
printf(tmpbuf);
【c语言中有时间函数吗 c语言时间类型】 }
运行结果:
Today is Saturday, day 30 of July in the year 2005.
8. 计算持续时间的长度
有时候在实际应用中要计算一个事件持续的时间长度,比如计算打字速度 。在第1节计时部分中,我已经用clock函数举了一个例子 。Clock()函数可以精确到毫秒级 。同时,我们也可以使用difftime()函数,但它只能精确到秒 。该函数的定义如下:
double difftime(time_t time1, time_t time0);
虽然该函数返回的以秒计算的时间间隔是double类型的,但这并不说明该时间具有同double一样的精确度,这是由它的参数觉得的(time_t是以秒为单位计算的) 。比如下面一段程序:
//计算持续时间的长度
/* Date : 10/24/2007 */
/* Author: Eman Lee */
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
int main(void)
{
time_t start,end;
start = time(NULL);
system("pause");
end = time(NULL);
printf("The pause used %f seconds. ",difftime(end,start));//-
system("pause");
return 0;
}
运行结果为:
请按任意键继续. . .
The pause used 2.000000 seconds.
请按任意键继续. . .
可以想像,暂停的时间并不那么巧是整整2秒钟 。其实 , 你将上面程序的带有“//-”注释的一行用下面的一行代码替换:
printf("The pause used %f seconds. ",end-start);
其运行结果是一样的 。
9. 分解时间转化为日历时间
这里说的分解时间就是以年、月、日、时、分、秒等分量保存的时间结构 , 在C/C++中是tm结构 。我们可以使用mktime()函数将用tm结构表示的时间转化为日历时间 。其函数原型如下:
time_t mktime(struct tm * timeptr);
其返回值就是转化后的日历时间 。这样我们就可以先制定一个分解时间,然后对这个时间进行操作了 , 下面的例子可以计算出1997年7月1日是星期几:
//计算出1997年7月1日是星期几
/* Date : 10/24/2007 */
/* Author: Eman Lee */
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
int main(void)
{
struct tm time;
time_t t_of_day;
time.tm_year=1997-1900;
time.tm_mon=6;
time.tm_mday=1;
time.tm_hour=0;
time.tm_min=0;
time.tm_sec=1;
time.tm_isdst=0;
t_of_day=mktime(time);
printf(ctime(t_of_day));
return 0;
}
运行结果:
Tue Jul 01 00:00:01 1997
有了mktime()函数,是不是我们可以操作现在之前的任何时间呢?你可以通过这种办法算出1945年8月15号是星期几吗?答案是否定的 。因为这个时间在1970年1月1日之前,所以在大多数编译器中,这样的程序虽然可以编译通过,但运行时会异常终止 。
注:linux系统时间如果转换为 time_t 类型,都是从1970-01-01 08:00:00 开始计算
C语言时间函数time_t1、time_t // 时间类型(time.h 定义)
struct tm { // 时间结构c语言中有时间函数吗,time.h 定义如下c语言中有时间函数吗:
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;
}
time ( rawtime ); // 获取时间c语言中有时间函数吗,以秒计,从1970年1月一日起算 , 存于rawtime
localtime ( rawtime ); //转为当地时间,tm 时间结构
asctime() // 转为标准ASCII时间格式:

推荐阅读