国际访客建议访问 Primers 编程伙伴 国际版站点 > C 教程 > localtime_s 以获得更好的体验。

# C 语言标准库函数 localtime_s

在头文件 time.h 中定义。
/*********************************************
 * @brief 将时间戳转换为结构体 struct tm
 * @param t 要被转换的时间
 * @param[out] buf 返回转换后的时间结构体
 * @return 转换后的时间结构体
 ********************************************/
struct tm* localtime_s(const time_t* restrict t, struct tm* restrict buf);

!subtitle:说明

将日历时间从时间戳 time_t 转换为本地时间的结构体 tm

!subtitle:参数

  • t - 要被转换的日历时间

  • buf - 返回转换后的时间结构体

!subtitle:返回值

  • 返回 buf

# 示例

#include <stdio.h>
#include <time.h>

int main(void)
{
    time_t t = time(NULL);

    struct tm tm;
    localtime_s(&t, &tm);
    printf("本地时间为 %s", asctime(&tm));

    return 0;
}

运行结果:

本地时间为 Thu Oct 16 10:44:44 2025

# 推荐阅读

# 参考标准

  • C23 standard (ISO/IEC 9899:2024):

    • K.3.8.2.4 The localtime_s function (p: TBD)

  • C17 standard (ISO/IEC 9899:2018):

    • K.3.8.2.4 The localtime_s function (p: 454-455)

  • C11 standard (ISO/IEC 9899:2011):

    • K.3.8.2.4 The localtime_s function (p: 626-627)

本文 更新于: 2025-11-27 09:38:09 创建于: 2025-11-27 09:38:09