由于UNIX内核提供的基本时间服务是国际标准时间公元1970年1月1日00:00:00以来经过的秒数。称其为日历时间。
time函数返回当前日期和时间
-
#include <time.h>
-
time_t time(time_t *t);
-
返回值:成功返回时间值,出错返回-1
与time函数相比,gettimeofday提供了更高的分辨率:
-
#include <sys/time.h>
-
int gettimeofday(struct timeval *tv, struct timezone *tz);
-
返回值:总是返回0
gettimeofday函数将当前的时间存放在tv指向的timeval结构中,该结构存储秒和微秒:
-
struct timeval {
-
time_t tv_sec; /* seconds */
-
suseconds_t tv_usec; /* microseconds */
-
};
通常要将日历时间转换为人们可读的时间和日期, 如下图:
两个函数localtime 和 gtime将日历时间转换为年、月、日、时、分、秒等表示的时间,
并将这些存放在tm结构中:
-
struct tm {
-
int tm_sec; /* seconds */
-
int tm_min; /* minutes */
-
int tm_hour; /* hours */
-
int tm_mday; /* day of the month */
-
int tm_mon; /* month */
-
int tm_year; /* year */
-
int tm_wday; /* day of the week */
-
int tm_yday; /* day in the year */
-
int tm_isdst; /* daylight saving time */
-
};
The members of the tm structure are:
tm_sec The number of seconds after the minute, normally in the range
0 to 59, but can be up to 60 to allow for leap seconds.
tm_min The number of minutes after the hour, in the range 0 to 59.
tm_hour The number of hours past midnight, in the range 0 to 23.
tm_mday The day of the month, in the range 1 to 31.
tm_mon The number of months since January, in the range 0 to 11.
tm_year The number of years since 1900.
tm_wday The number of days since Sunday, in the range 0 to 6.
tm_yday The number of days since January 1, in the range 0 to 365.
tm_isdst A flag that indicates whether daylight saving time is in
effect at the time described. The value is positive if day-
light saving time is in effect, zero if it is not, and nega-
tive if the information is not available.
-
#include <time.h>
-
-
struct tm *gmtime(const time_t *timep);
-
struct tm *gmtime_r(const time_t *timep, struct tm *result);
-
-
struct tm *localtime(const time_t *timep);
-
struct tm *localtime_r(const time_t *timep, struct tm *result);
-
两种类型的函数返回值:指向tm结构的指针
localtime和gmtime函数的区别:localtime将日历时间转换为本地时间, 而gmtime则将日历时间转换为国际标准时间。
-
#include <time.h>
-
time_t mktime(struct tm *tm);
-
返回值:若成功则返回日历时间,出错返回-1
mktime函数将本地时间年月日等作为参数,转换为time_t值;
-
#include <time.h>
-
-
char *asctime(const struct tm *tm);
-
char *asctime_r(const struct tm *tm, char *buf);
-
-
char *ctime(const time_t *timep);
-
char *ctime_r(const time_t *timep, char *buf);
-
返回值:指向以null结尾的字符串的指针
这两种类型的函数将产生熟悉的26字节的字符串类似date命令
演示:
-
#include <stdio.h>
-
#include <time.h>
-
-
int main(int argc, char *argv[])
-
{
-
time_t cutime;
-
struct tm *timeinfo;
-
-
cutime = time(NULL);
-
timeinfo = localtime(&cutime);
-
printf(asctime(timeinfo));
-
-
return 0;
-
}
结果显示:
$ ./a.out
Sat Dec 6 01:43:55 2014
时间函数strftime,类似于printf的时间函数:
-
#include <time.h>
-
size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);
-
返回值:若有空间则返回存入数组的字符串,否则返回0
strftime的转换说明:
阅读(1429) | 评论(0) | 转发(0) |