Linux C编程基础知识(日期与时间操作)

张开发
2026/6/19 23:51:15 15 分钟阅读
Linux C编程基础知识(日期与时间操作)
常用API介绍函数功能说明time_t time(time_t *t)获取当前 Unix 时间戳秒级参数传 NULL 即可struct tm *localtime(const time_t *timep)将时间戳转换为本地时间的分解结构体含时区struct tm *gmtime(const time_t *timep)将时间戳转换为UTC 时间的分解结构体无时区char *ctime(const time_t *timep)将时间戳转为可读字符串如 Mon Feb 09 12:34:56 2026char *asctime(const struct tm *tm)将分解结构体转为可读字符串格式同 ctimesize_t strftime(char *s, size_t max, const char *format, const struct tm *tm)自定义格式化时间字符串核心clock_t clock(void)获取程序启动后的 CPU 时钟滴答数用于计时strftime 是最常用的时间格式化函数支持自定义输出格式如 YYYY-MM-DD HH:MM:SS核心格式符如下格式符含义示例%Y4 位年份2026%m2 位月份补 002%d2 位日期补 009%H24 小时制小时12%M2 位分钟34%S2 位秒数56%A星期全称Monday%a星期简称Mon示例获取当前时间时间戳 可读格式#include stdio.h #include time.h int main() { // 1. 获取当前Unix时间戳秒级 time_t now time(NULL); printf(当前Unix时间戳秒%lld\n, (long long)now); // 强转long long避免溢出 // 2. 转换为本地时间的分解结构体 struct tm *local_tm localtime(now); if (local_tm NULL) { // 容错转换失败返回NULL perror(localtime failed); return 1; } // 3. 直接输出可读字符串ctime printf(本地时间ctime%s, ctime(now)); // 自带换行 // 4. 解析分解结构体的字段注意年份是1900偏移月份从0开始 printf(分解时间字段\n); printf( 年%d\n, local_tm-tm_year 1900); // tm_year 年份-1900 printf( 月%d\n, local_tm-tm_mon 1); // tm_mon 0~111月0 printf( 日%d\n, local_tm-tm_mday); // 日1~31 printf( 时%d\n, local_tm-tm_hour); // 时0~23 printf( 分%d\n, local_tm-tm_min); // 分0~59 printf( 秒%d\n, local_tm-tm_sec); // 秒0~60闰秒 printf( 星期%d\n, local_tm-tm_wday); // 星期0~6周日0 return 0; }示例格式化输出「年 - 月 - 日 时分: 秒」#include stdio.h #include time.h int main() { time_t now time(NULL); struct tm *local_tm localtime(now); if (local_tm NULL) { perror(localtime failed); return 1; } // 定义缓冲区存储格式化结果足够容纳时间字符串 char time_buf[64]; // 自定义格式YYYY-MM-DD HH:MM:SS strftime(time_buf, sizeof(time_buf), %Y-%m-%d %H:%M:%S, local_tm); printf(格式化本地时间%s\n, time_buf); // 输出2026-02-09 12:34:56 // 另一种格式星期 月 日 时:分:秒 年 strftime(time_buf, sizeof(time_buf), %A %b %d %H:%M:%S %Y, local_tm); printf(完整格式%s\n, time_buf); // 输出Monday Feb 09 12:34:56 2026 return 0; }

更多文章