◆time()
取得当前时间。此函数会返回从公元1970年1月1日的UTC时间从0时0分0秒算起到现在所经过的秒数。如果参数t为非空指针的话, 此函数也会将返回值存到t指针所指的内存。
成功则返回秒数, 失败则返回((time_t)-1)值, 错误原因存于errno中。
#include <time.h>
time_t time(time_t *t);
例:
#include <time.h>
#include <stdio.h> int main()
{ int seconds = time((time_t *)NULL);
printf("%d\n", seconds); return ;
}
运行结果:1517968358
◆gmtime()
返回当时时间,不过该函数返回的时间日期未经时区转换, 而是UTC时间
#include <time.h>
struct tm *gmtime(const time_t *timep);
例:
#include <time.h>
#include <stdio.h> int main()
{ char *wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
time_t timep;
struct tm *p; time(&timep);
p = gmtime(&timep); printf("%d/%d/%d \n", (+p->tm_year), (+p->tm_mon), p->tm_mday);
printf("%s %d:%d:%d\n", wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec);
return ;
}
运行结果:
2018/2/7
Wed 1:55:53
◆localtime()
取得当地目前的时间和日期。与gmtime()函数不同的是,该函数返回的时间日期已经转换成当地时区。
#include <time.h>
struct tm *localtime(const time_t *timep);
例:
#include <stdio.h>
#include <time.h> int main()
{ char *wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};\
time_t timep;
struct tm *p; time(&timep);
// Get local time
p = localtime(&timep);
printf("%d/%d/%d ", (+p->tm_year), (+p->tm_mon), p->tm_mday);
printf("%s %d:%d:%d\n", wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec);
return ;
}
运行结果:
2018/2/7 Wed 10:0:32
◆strftime()
格式化日期时间。该函数会把结构体tm根据format所指定的字符串格式做转换,并将转换后的内容复制到参数s所指的字符串数组中。
#include <time.h>
size_t strftime(char *s, size_t max, const char *format,
const struct tm *tm);
例:
#include <time.h>
#include <stdio.h> int main()
{ char *format[] = {"%I, %M, %S, %p, %m/%d %a", "%x %X %Y", NULL};
char buf[];
int i;
time_t clock;
struct tm *tm;
time(&clock);
tm = gmtime(&clock); for (i = ; format[i] != NULL; i++) {
strftime(buf, sizeof(buf), format[i], tm);
printf("%s=> %s\n", format[i], buf);
}
return ;
}
运行结果:
%I, %M, %S, %p, %m/%d %a=> 02, 04, 53, AM, 02/07 Wed
%x %X %Y=> 02/07/18 02:04:53 2018