c语言调用精确时间函数 c++精确时间( 三 )


运行的结果与当时的时间有关,我当时运行的'结果是:
/* Date : 10/24/2007 */
/* Author: Eman Lee */
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
int main(void)
【c语言调用精确时间函数 c++精确时间】 {
time_t lt;
lt =time(NULL);
printf("The Calendar Time now is %d ",lt);
return 0;
}
The Calendar Time now is 1122707619
其中1122707619就是我运行程序时的日历时间 。即从1970-01-01 08:00:00到此时的秒数 。
5. 获得日期和时间
这里说的日期和时间就是我们平时所说的年、月、日、时、分、秒等信息 。从第2节我们已经知道这些信息都保存在一个名为tm的结构体中,那么如何将一个日历时间保存为一个tm结构的对象呢?
其中可以使用的函数是gmtime()和localtime(),这两个函数的原型为:
struct tm * gmtime(const time_t *timer);
struct tm * localtime(const time_t * timer);
其中gmtime()函数是将日历时间转化为世界标准时间(即格林尼治时间),并返回一个tm结构体来保存这个时间,而localtime()函数是将日历时间转化为本地时间 。比如现在用gmtime()函数获得的世界标准时间是2005年7月30日7点18分20秒,那么我用localtime()函数在中国地区获得的本地时间会比世界标准时间晚8个小时,即2005年7月30日15点18分20秒 。下面是个例子:
//本地时间,世界标准时间
/* Date : 10/24/2007 */
/* Author: Eman Lee */
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
int main(void)
{
struct tm *local;
time_t t;
t=time(NULL);
local=localtime(t);
printf("Local hour is: %d:%d:%d ",local-tm_hour,local-tm_min,local-tm_sec);
local=gmtime(t);
printf("UTC hour is: %d:%d:%d ",local-tm_hour,local-tm_min,local-tm_sec);
return 0;
}
运行结果是:
Local hour is: 23:17:47
UTC hour is: 15:17:47
6. 固定的时间格式
我们可以通过asctime()函数和ctime()函数将时间以固定的格式显示出来,两者的返回值都是char*型的字符串 。返回的时间格式为:
星期几 月份 日期 时:分:秒 年
例如:Wed Jan 02 02:03:55 1980
其中 是一个换行符,是一个空字符,表示字符串结束 。下面是两个函数的原型:
char * asctime(const struct tm * timeptr);
char * ctime(const time_t *timer);
其中asctime()函数是通过tm结构来生成具有固定格式的保存时间信息的字符串,而ctime()是通过日历时间来生成时间字符串 。这样的话,asctime()函数只是把tm结构对象中的各个域填到时间字符串的相应位置就行了,而ctime()函数需要先参照本地的时间设置,把日历时间转化为本地时间,然后再生成格式化后的字符串 。在下面,如果t是一个非空的time_t变量的话 , 那么:
printf(ctime(t));
等价于:
struct tm *ptr;
ptr=localtime(t);
printf(asctime(ptr));
那么,下面这个程序的两条printf语句输出的结果就是不同的了(除非你将本地时区设为世界标准时间所在的时区):
//本地时间,世界标准时间
/* Date : 10/24/2007 */
/* Author: Eman Lee */
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
int main(void)
{
struct tm *ptr;
time_t lt;
lt =time(NULL);
ptr=gmtime();
printf(asctime(ptr));
printf(ctime());
return 0;
}
运行结果:
Sat Jul 30 08:43:03 2005
Sat Jul 30 16:43:03 2005
7. 自定义时间格式
我们可以使用strftime()函数将时间格式化为我们想要的格式 。它的原型如下:

推荐阅读