Unix时间和日期

      Unix内核提供的基本时间服务是计算自国际标准时间19701100:00:00以来经历的秒数(time_t类型)。Unix系统中时间戳一般32位数据存储,2038年,32位数将溢出。

 

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

#include <time.h> 

time_t time(time_t *time);

时间总是作为函数返回值。如果参数不为空,则时间值放入time指针指向的内存单元。

 

 

gettimeofday提供更高的时间分辨率(微秒)

#include <sys/time.h>

int gettimeofday(struct timeval *tv, void * tz); //第二个参数某些平台表示时区信息

struct timeval

{

     time_t tv_sec;  /* seconds  */

     time tv_usec;   /* microseconds */

};

 

 

localtimegmtime将日历时间转换以年,月,日,时,分,秒表示的时间,并存放到struct tm结构中。

struct tm

{ /* a broken-down time */

int tm_sec; /* seconds after the minute: [0, 61] */

int tm_min; /* minutes after the hour: [0, 59] */

int tm_hour; /* hours after midnight: [0, 23] */

int tm_mday; /* day of the month: [1, 31] */

int tm_mon; /* month of the year: [0, 11] */

int tm_year; /* years since 1900 */

int tm_wday; /* days since Sunday: [0, 6] */

int tm_yday; /* days since January 1: [0, 365] */

int tm_isdst; /* daylight saving time flag: <0, 0, >0 */

} ;

 

 

localtimegmtime的区别是:localtime将日历时间转换成本地时间(考虑到本地的时区和夏时制标志),而gmtime将日历转换成国际标准时间的年,月,日,时…..

#include <time.h>

struct tm *gmtime(const time_t *time);

struct tm *localtime(const time_t *time);

 

 

函数mktimetm结构为参数,返回time_t类型值

#include <time.h>

time_t mktime(struct tm* tmptr);

 

 

asctimectime产生时间字符串,前者以tm结构为参数,后者以time_t为参数。

Tue Feb 18:30:20  2009\12\17

#include <time.h>

char *asctime(const struct tm* tmptr);

char *ctime(const time_t *time);

 

 

strftime类似与printf,将时间格式化到一个缓冲区中

#include <time.h>

size_t strftime(char *buf size_t maxsize, const char *format, const struct tm *tmptr);

其中format格式如%s代表秒,详情man strftime看查看所有参数。

 

几种时间格式的转换图如下:

 

<IMG border=0 src="http://blogimg.chinaunix.net/blog/upfile2/091217100248.jpg" onload="javascript:if(this.width>500)this.width=500;">
posted @ 2013-04-19 14:04  ydzhang  阅读(413)  评论(0编辑  收藏  举报