您的位置:首页 > 编程语言

UNIX环境高级编程读书笔记(六)—时间和日期 (2)

2008-08-19 19:02 246 查看
4.

名称::gmtime/localtime
功能:transform date and time
头文件:#include <time.h>
函数原形: struct tm *gmtime(const time_t *calptr)
struct tm *locatltime(const time_t calptr);
参数:calptr time_t类型的时间
返回值:返回指向tm类型的指针。
localtime和gmtime之间的区别是:localtime将日历时间转换成为本地时间,而gmtiem将日历时间转换为国际标准时间。两个函数的返回值类型都是tm.该类型的定义如下。
struct tm{
int tm_sec;
int tm_min;
int tm_hout;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
};
下面是一个例子,打印当前系统的本地时间和国际标准时间。

/*6_2.c*/
#include <stdio.h>
#include <time.h>

main()
{
time_t ti;
struct tm *gtime;
strcut tm *ltime;

if((ti=time(NULL))<0)
perror(“error”);
gtime=(struct tm*)malloc(sizeof(struct tm));
ltime=( struct tm*)malloc(sizeof(struct tm));
if((gtime=gmtime(&ti))<0)
perror(“error”);
if((ltime=localtime(&ti))<0)
perror(“error”);
printf(“gmtime:%d year %d month %d day %d:%d:%d/n”,gtime->tm_year,
gtime->tm_mon,gtime->tm_mday,gtime->tm_ hour,gtime->tm_min,gtime->tm_sec);
printf(“localtime:%d year %d month %d day %d:%d:%d/n”,ltime->tm_year,
ltime->tm_mon,ltime->tm_mday,ltime->tm_ hour,ltime->tm_min,ltime->tm_sec);
free(gtime);
free(ltime);
}
5.

名称::mktime
功能:transform date and time
头文件:#include <time.h>
函数原形: time_t mktime(struct tm *tmptr);
参数:tmptr
返回值:若成功则返回日历时间,若出错则返回-1
mktime以本地时间的年,月,日等为参数,将其转换成time_t型。是locatltime函数的功能正好相反。

6.

名称::ctime/asctime
功能:transform date and time
头文件:#include <time.h>
函数原形: char *asctiem(const struct tm *tmptr);
char *ctime(const time_t *calptr);
参数:tmptr tmptr类型时间值
calptr calptr类型时间值
返回值:指向以NULL结尾的字符串指针
Asctime和ctime函数产生形式的26字节字符串,这与date(1)命令的系统默认输出形式类似:
Wed Oct 4 07:13:20 CST 2006

7.

名称::strftime
功能:format date and time
头文件:#include <time.h>
函数原形: size_t strftime(char *s,size_t max,const char *format,const struct tm *tm);
参数:
返回值:若有空间则返回存入数组的字符数,否则返回0。
下面是应用这些函数的一个程序:

/*6_3.c*/
#include <time.h>
main()
{
time_t *nowtime;
struct tm *gtime;
struct tm *ltime;
char *t1;
char *t2;

time(nowtime);
gtime=gmtime(nowtime);
ltime=localtime(nowtime);

t1=ctime(nowtime);
t2=asctme(gtime);

printf(“time:%s/n”,t1);
printf(“time:%s/n”,t2);
printf(“hour:%d min:%d sec:%d/n”,gtime->tm_hour,gtime->tm_min,gtime->tm_sec);
free(nowtime);
free(gtime);
free(ltime);
}
文章转自:http://blog.chinaunix.net/u1/59291/showart.php?id=538558
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: