UNIX环境高级编程——时间和日期

     由UNIX内核提供的基本时间服务是计算自国际标准时间公元1970年1月1日00:00:00以来经过的秒数。这种秒数是以数据类time_t表示。

    

1.     time函数返回当前时间和日期:

time_t time(time_t *calptr);
     时间值总是作为函数返回。如果参数不为空,则时间值也存放在由calptr指向的单元内。


2.     与time函数相比,gettimeofday提供了更高的分辨率(最高位微秒级)。

int gettimeofday(struct timeval* tp,void* tzp);

     tzp的唯一合法值是NULL,其他值则将产生不确定的结果。

     gettimeofday函数将当前时间存放在tp指向的timeval结构中,而该结构存储秒和微妙。

struct timeval{
long int tv_sec; // 秒数
long int tv_usec; // 微秒数
}

3.     两个函数localtime和gmtime将日历时间转换成以年、月、日、时、分、秒、周日表示的时间,并将这些存放在一个tm结构中。

struct tm
{
int tm_sec;//代表目前秒数,正常范围为0-59,但允许至61秒
int tm_min;//代表目前分数,范围0-59
int tm_hour;//从午夜算起的时数,范围为0-23
int tm_mday;//目前月份的日数,范围01-31
int tm_mon;//代表目前月份,从一月算起,范围从0-11
int tm_year;//从1900 年算起至今的年数
int tm_wday;//一星期的日数,从星期一算起,范围为0-6
int tm_yday;//从今年1月1日算起至今的天数,范围为0-365
int tm_isdst;//夏令时当前是否生效
};

struct tm *localtime(const time_t *clock);
struct tm *gmtime(const time_t *clock);

     localtime和gmtime之间的区别是:localtime将日历时间转换成本地时间(考虑到本地时区和夏时制标志),而gmtime则将日历时间转换成国际标准时间的年、月、日、时、分、秒、周日。


4.     函数mktime以本地时间的年、月、日等作为参数,将其转换成time_t值。

time_t mktime(struct tm* tmptr);

     

5.     asctime和ctime函数产生大家熟悉的26字节的字符串,这与date(1)命令的系统默认输出类似,例如:

huangcheng@ubuntu:~$ date
2013年 07月 05日 星期五 18:25:52 CST

char* asctime(const struct tm* tmptr);
char* ctime(const time_t calptr);

     asctime的参数是指向年、月、日等字符串的指针,而ctime的参数则是指向日历时间的指针。







原文地址:https://www.cnblogs.com/wangfengju/p/6172826.html