4.与日期和时间相关的函数及应用
在本节,我将向大家展示怎样利用time.h中声明的函数对时间进行操作。这些操作包括取当前时间、计算时间间隔、以不同的形式显示时间等内容。
4.1 获得日历时间
我们可以通过time()函数来获得日历时间(calendar time),其原型为:time_t time(time_t * timer);
如果你已经声明了参数timer,你可以从参数timer返回现在的日历时间,同时也可以通过返回值返回现在的日历时间,即从一个时间点(例如:1970 年1月1日0时0分0秒)到现在此时的秒数。如果参数为空(nul),函数将只通过返回值返回现在的日历时间,比如下面这个例子用来显示当前的日历时间:
#include "time.h"
#include "stdio.h"
int main(void)
{
struct tm *ptr;
time_t lt;
lt =time(nul);
printf("the calendar time now is %d\n",lt);
return 0;
}
运行的结果与当时的时间有关,我当时运行的结果是:
the calendar time now is 1122707619
其中1122707619就是我运行程序时的日历时间。即从1970年1月1日0时0分0秒到此时的秒数。
4.2 获得日期和时间
这里说的日期和时间就是我们平时所说的年、月、日、时、分、秒等信息。从第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秒。下面是个例子:
#include "time.h"
#include "stdio.h"
int main(void)
{
struct tm *local;
time_t t;
t=time(nul);
local=localtime(&t);
printf("local hour is: %d\n",local->tm_hour);
local=gmtime(&t);
printf("utc hour is: %d\n",local->tm_hour);
return 0;
}
运行结果是:
local hour is: 15
utc hour is: 7
4.3 固定的时间格式
我们可以通过asctime()函数和ctime()函数将时间以固定的格式显示出来,两者的返回值都是char*型的字符串。返回的时间格式为:
星期几 月份 日期 时:分:秒 年\n\0
例如:wed jan 02 02:03:55 1980\n\0
其中\n是一个换行符,\0是一个空字符,表示字符串结束。下面是两个函数的原型:
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语句输出的结果就是不同的了(除非你将本地时区设为世界标准时间所在的时区):
#include "time.h"
#include "stdio.h"
int main(void)
{
struct tm *ptr;
time_t lt;
lt =time(nul);
ptr=gmtime(<);
printf(asctime(ptr));
printf(ctime(<));
return 0;
}
运行结果:
sat jul 30 08:43:03 2005
sat jul 30 16:43:03 2005
| 广告合作:400-664-0084 全国热线:400-664-0084 Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号 珠峰网 版权所有 All Rights Reserved
|