由UNIX内核提供的基本时间服务是国际标准时间公元1970年1月1日00:00:00以来经过的秒数。这种秒数是以数据类型 time_t表示的。我们称它们为日历时间,由函数time()内的系统调用获取。
#include <time.h>
time_t time(time_t *tloc);//时间值作为函数值返回。如果参数非 n u l l,则时间值也存放在由tloc指向的单元内
tm结构
struct tm {
int tm_sec; /* Seconds (0-60) */
int tm_min; /* Minutes (0-59) */
int tm_hour; /* Hours (0-23) */
int tm_mday; /* Day of the month (1-31) */
int tm_mon; /* Month (0-11) */
int tm_year; /* Year - 1900 */
int tm_wday; /* Day of the week (0-6, Sunday = 0) */
int tm_yday; /* Day in the year (0-365, 1 Jan = 0) */
int tm_isdst; /* Daylight saving time */
};
time_t和tm结构可通过下面的函数转换
#include <time.h>
//使用 timep 的值来填充 tm 结构,并用格林尼治标准时间(GMT)表示。
struct tm *gmtime(const time_t *timep);
struct tm *gmtime_r(const time_t *timep, struct tm *result);
//使用 timep 的值来填充 tm 结构,并用本地时区表示。
struct tm *localtime(const time_t *timep);
struct tm *localtime_r(const time_t *timep, struct tm *result);
//以本地时间的tm结构作为参数,将其变换成 time _ t值
time_t mktime(struct tm *tm);
将time_t或tm表示成字符串,形如 “Wed Jun 30 21:49:08 1993\n”
#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);
strftime函数根据 format 中定义的格式化规则,格式化结构 tm 表示的时间,并把它存储在s中。如果产生的字符串小于 size 个字符(包括空结束字符),则会返回复制到 str 中的字符总数(不包括空结束字符),否则返回零。
#include <time.h>
size_t strftime(char *s, size_t max, const char *format,
const struct tm *tm);
| 格 式 | 说 明 | 例 子 |
|---|---|---|
| % a | 缩写的周日名 | T u e |
| % A | 全周日名 | T u e s d a y |
| % b | 缩写的月名 | J a n |
| % B | 月全名 | J a n u a r y |
| % c | 日期和时间 Tue Jan 14 19:40:30 | 1992 |
| % d | 月日: [01, 31] | 1 4 |
| % H | 小时(每天2 4小时): [00, 23] | 1 9 |
| % I | 小时(上、下午各 1 2小时): [01, 12] | 0 7 |
| % j | 年日: [001, 366] | 0 1 4 |
| % m | 月: [01, 12] | 0 1 |
| % M | 分: [00, 59] | 4 0 |
| % p | A M / P M | P M |
| % S | 秒:[00, 61] | 3 0 |
| % U | 星期日周数: [00, 53] | 0 2 |
| % w | 周日: [ 0 =星期日, 6 ] | 2 |
| % W | 星期一周数: [00, 53] | 0 2 |
| % x | 日期 | 0 1 / 1 4 / 9 2 |
| % X | 时间 | 1 9 : 4 0 : 3 0 |
| % y | 不带公元的年: [00, 991] | 9 2 |
| % Y | 带公元的年 | 1 9 9 2 |
| % Z | 时区名 | M S T |