ILD

time api
作者:Yuan Jianpeng 邮箱:yuanjp89@163.com
发布时间:2026-5-21 站点:Inside Linux Development

头文件time.h


获取当前时间戳

获取当前时刻距Epoch的秒数。Epoch:1970-01-01 00:00:00 +0000 (UTC)

time_t time(time_t *_Nullable tloc);

这是一个系统调用,如果失败,返回(time_t)-1.

可以称为UTC时间戳。


Broken-down time

man 3 tm

       struct tm {
           int         tm_sec;    /* Seconds          [0, 60] */
           int         tm_min;    /* Minutes          [0, 59] */
           int         tm_hour;   /* Hour             [0, 23] */
           int         tm_mday;   /* Day of the month [1, 31] */
           int         tm_mon;    /* Month            [0, 11]  (January = 0) */
           int         tm_year;   /* Year minus 1900 */
           int         tm_wday;   /* Day of the week  [0, 6]   (Sunday = 0) */
           int         tm_yday;   /* Day of the year  [0, 365] (Jan/01 = 0) */
           int         tm_isdst;  /* Daylight savings flag */

           /* Since POSIX.1-2024:  */
           long        tm_gmtoff; /* Seconds East of UTC */
           const char *tm_zone;   /* Timezone abbreviation */
       };



时间戳转broken down time

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

gmtime是转换成Coordinated Universal Time (UTC)

localtime转换成本地时间。

还有对应的线程安全版本,如localtime_r。


broken down time转UTC时间戳

time_t timegm(struct tm *tm);
[[deprecated]] time_t timelocal(struct tm *tm);

time_t mktime(struct tm *tm);

timegm是gmtime的逆函数。

timelocal和mktime是等价的,后者是POSIX函数,所以timelocal被返回。它们是localtime的逆函数。


timezone

man 3 timezone

void tzset(void);

       extern char *tzname[2];
       extern long timezone;
       extern int daylight;

在调用和时区相关的函数时,会自动调用tzset()


如果要切换时区等,也可以手动调用tzset()。它从TZ环境变量初始化,如果没有。

从/etc/localtime初始化。这个文件一般是个符号链接,指向一个时区文件。如:

/etc/localtime -> /usr/share/zoneinfo/Asia/Shanghai


时间转字符串

char *asctime(const struct tm *tm);
char *ctime(const time_t *timep);

前者是broken-down time转字符串。后者是时间戳转本地时间字符串。

这两个函数也有对应的线程安全版本,如ctime_r。

字符串格式:"Wed Jun 30 21:49:08 1993\n"

ctime会初始化时区相关变量。


格式化日期和时间

man 3 strftime


size_t strftime(size_t max;
                       char s[restrict max], size_t max,
                       const char *restrict format,
                       const struct tm *restrict tm);

和printf一样,可以输出时间的特定部分。比如输出年月日时分秒:

strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", tm);


字符串转时间

man 3 strptime

char *strptime(const char *restrict s, const char *restrict format,
                      struct tm *restrict tm);

类似sscanf,将字符串,按特定格式,转换为tm。







Copyright © linuxdev.cc 2017-2024. Some Rights Reserved.