C 语言 - 日期和时间
时间与日期
在 C 语言中,您可以使用 <time.h> 头文件来处理日期和时间。
这个库允许您获取当前时间、格式化时间以及执行与时间相关的计算。
获取当前时间
<time.h> 库有各种测量日期和时间的函数。
例如,time() 函数以 time_t 类型的值返回当前时间。
您可以使用 ctime() 将时间转换为可读的字符串,例如 "Mon Jun 24 10:15:00 2025":
实例
#include <stdio.h>
#include <time.h>
int main() {
time_t currentTime;
time(¤tTime); // 获取当前时间
printf("Current time: %s", ctime(¤tTime));
return 0;
}
分解时间
如果您想访问日期或时间的各个部分,例如年、月或小时,可以使用 localtime() 函数。
此函数将当前时间(来自 time())转换为 struct tm,这是一个特殊的结构体,它将日期和时间存储在单独的字段中。
以下是使用它打印当前日期和时间的每个部分的方法:
实例
#include <stdio.h>
#include <time.h>
int main() {
time_t now = time(NULL); // 获取当前时间
struct tm *t = localtime(&now); // 转换为本地时间结构体
printf("Year: %d\n", t->tm_year + 1900); // 加 1900 得到实际年份
printf("Month: %d\n", t->tm_mon + 1); // 月份从 0 到 11 编号,因此加 1 以匹配实际月份数字 (1-12)
printf("Day: %d\n", t->tm_mday);
printf("Hour: %d\n", t->tm_hour);
printf("Minute: %d\n", t->tm_min);
printf("Second: %d\n", t->tm_sec);
return 0;
}
格式化日期和时间
您可以使用 strftime() 将日期和时间格式化为字符串:
实例
#include <stdio.h>
#include <time.h>
int main() {
time_t now = time(NULL);
struct tm *t = localtime(&now);
char buffer[100];
strftime(buffer, sizeof(buffer), "%d-%m-%Y %H:%M:%S", t);
printf("Formatted time: %s\n", buffer);
return 0;
}
何时使用日期和时间
在 C 语言中使用日期和时间,当您想要:
- 显示当前时间或日期
- 记录事件,如错误或用户操作
- 为文件或消息添加时间戳
- 测量某件事花费的时间
- 计划或延迟操作
- 为随机数生成种子(以便每次运行得到不同的结果)