C time (time.h) 库

C 语言时间函数

<time.h> 头文件提供了在 C 语言中处理日期、时间和测量持续时间的函数。

下表列出了常见的 time.h 函数:

函数 描述
time() 将当前日历时间作为 time_t 值返回(自 1970 年 1 月 1 日以来的秒数)。
localtime() time_t 值转换为本地时间,并返回一个指向 struct tm 的指针。
gmtime() time_t 值转换为 UTC 时间(也作为 struct tm)。
ctime() time_t 值转换为可读的字符串(例如 Thu Jun 26 10:30:00 2025)。
asctime() struct tm 转换为标准日期/时间格式的字符串。
strftime() struct tm 格式化为自定义的日期和时间字符串。
difftime() 计算两个 time_t 值之间的差值(以秒为单位)。
mktime() 将填充好的 struct tm 转换为 time_t 值。
clock() 返回程序使用的处理器时钟滴答数(可用于测量执行时间)。

什么是 struct tm?

有几个函数返回或使用一个名为 struct tm 的特殊结构体,它包含日期和时间的各个部分,如年、月、小时和分钟。

您可以使用此结构体分别格式化和访问每个时间组件。