关于用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结构表示的时间转化为日历时间 。其函数原型如下:
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语言编写一个显示时间的函数,要求时间显示精度到毫秒级别 。#include cstdio
#include ctime
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void printTime() {
struct tm t;//tm结构指针
time_t now;//声明time_t类型变量
time(now);//获取系统日期和时间
localtime_s(t, now);//获取当地日期和时间
//格式化输出本地时间
printf("年-月-日-时-分-秒用c语言显示系统时间函数:%d-%d-%d %d:%d:%d\n", t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);
}
int main(int argc, char** argv) {
printTime();
}
C语言获取系统时间需要利用C语言的时间函数time和localtime用c语言显示系统时间函数,具体说明如下用c语言显示系统时间函数:
一、函数接口介绍:
1、time函数 。
形式为time_t time (time_t *__timer);
其中time_t为time.h定义的结构体用c语言显示系统时间函数,一般为长整型 。
这个函数会获取当前时间,并返回 。如果参数__timer非空,会存储相同值到__timer指向的内存中 。
time函数返回的为unix时间戳 , 即从1970年1月1日(UTC/GMT的午夜)开始所经过的秒数,不考虑闰秒 。
由于是秒作为单位的,所以这并不是习惯上的时间,要转为习惯上的年月日时间形式就需要另外一个函数用c语言显示系统时间函数了 。

推荐阅读