跳到主要内容

9. time.h — 日期与时间

提供日期与时间函数,按功能分组说明。

头文件说明:wcsftime 声明在 <wchar.h>,不在 <time.h>,使用时需要包含 <wchar.h>。

time_t time(time_t *tloc)

获取当前时间戳。

  • 输入: tloc 时间指针(可为 NULL,此时结果也存入 *tloc)
  • 输出: time_t 从 Epoch(1970-01-01 00:00:00 UTC)起的秒数
  • 注意: (time_t)-1 表示错误

clock_t clock(void)

获取处理器时间。

  • 输入: 无
  • 输出: clock_t 处理器滴答数
  • 注意: (clock_t)-1 表示错误,需除以 CLOCKS_PER_SEC 得秒数

double difftime(time_t time1, time_t time0)

计算时间差(秒)

  • 输入: time1 时间1, time0 时间0
  • 输出: double time1 - time0(秒)
  • 注意: 结果始终为 double,即使 time_t 是整数

time_t mktime(struct tm *tm)

分解时间转时间戳。

  • 输入: tm 分解时间结构(本地时间)
  • 输出: time_t 时间戳
  • 注意: 会规范化 tm 中各字段

struct tm* gmtime(const time_t *timer)

UTC 时间分解。

  • 输入: timer 时间戳指针
  • 输出: struct tm* UTC 分解时间
  • 注意: 返回静态缓冲区

struct tm* localtime(const time_t *timer)

本地时间分解。

  • 输入: timer 时间戳指针
  • 输出: struct tm* 本地分解时间
  • 注意: 返回静态缓冲区

char* asctime(const struct tm *tm)

时间转字符串。

  • 输入: tm 分解时间结构
  • 输出: char* "Www Mmm dd hh:mm:ss yyyy\n"
  • 注意: 返回静态缓冲区

char* ctime(const time_t *timer)

时间戳转字符串。

  • 输入: timer 时间戳指针
  • 输出: char* 时间字符串
  • 注意: 等价于 asctime(localtime(timer))

size_t strftime(char *buf, size_t maxsize, const char *fmt, const struct tm *tm)

格式化时间字符串。

  • 输入: buf 缓冲区, maxsize 大小, fmt 格式(如 "%Y-%m-%d"), tm 时间结构
  • 输出: size_t 写入字符数(不含\0),0 表示缓冲区不足或错误

size_t wcsftime(wchar_t *buf, size_t maxsize, const wchar_t *fmt, const struct tm *tm)

格式化宽字符时间字符串。

  • 输入: buf 宽缓冲区, maxsize 大小, fmt 宽格式, tm 时间结构
  • 输出: size_t 写入宽字符数