c语言转换时间函数 c语言时间转换为时间戳( 五 )


//计算持续时间的长度
/* 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结构表示的时间转化为日历时间 。其函数原型如下:
【c语言转换时间函数 c语言时间转换为时间戳】 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语言中系统时间函数是怎么用的??1、C语言中读取系统时间的函数为time()c语言转换时间函数 , 其函数原型为:
#include time.h
time_t time( time_t * ) ;
time_t就是longc语言转换时间函数,函数返回从1970年1月1日(MFC是1899年12月31日)0时0分0秒 , 到现在的的秒数 。
2、C语言还提供c语言转换时间函数了将秒数转换成相应的时间格式的函数:
char * ctime(const time_t *timer); //将日历时间转换成本地时间,返回转换后的字符串指针 可定义字符串或是字符指针来接收返回值
struct tm * gmtime(const time_t *timer); //将日历时间转化为世界标准时间(即格林尼治时间),返回结构体指针 可定义struct tm *变量来接收结果
struct tm * localtime(const time_t * timer); //将日历时间转化为本地时间,返回结构体指针 可定义struct tm *变量来接收结果
3、例程:
#include time.h
void main()
{
time_t t;
struct tm *pt ;
char *pc ;
time(t);
pc=ctime(t) ; printf("ctime:%s", pc );
pt=localtime(t) ; printf("year=%d", pt-tm_year+1900 );
}
//时间结构体struct tm 说明:
struct tm {
int tm_sec; /* 秒 – 取值区间为[0,59] */
int tm_min; /* 分 - 取值区间为[0,59] */
int tm_hour; /* 时 - 取值区间为[0,23] */
int tm_mday; /* 一个月中的日期 - 取值区间为[1,31] */
int tm_mon; /* 月份(从一月开始 , 0代表一月) - 取值区间为[0,11] */

推荐阅读