C 语言 strftime() 函数用于按自定义格式格式化时间,输出更灵活。
原型
size_t strftime(char *str, size_t count,
const char *format, const struct tm *tm);常用格式:%Y 年、%m 月、%d 日、%H 时、%M 分、%S 秒。
参数
str- 输出缓冲区;count- 缓冲区大小;format- 格式字符串;tm- 指向 struct tm 的指针。
示例
#include <stdio.h>
#include <time.h>
int main() {
time_t t = time(NULL);
struct tm *lt = localtime(&t);
char buf[64];
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", lt);
printf("%s\n", buf);
return 0;
}输出:
2024-10-02 12:34:56注意事项
strftime 是生成各种日期格式(文件名、日志)的标准方式。