C语言的<time.h>文件提供了一系列用于处理时间和日期的函数。这些函数包括获取当前时间、时间格式化、时间运算等,能够帮助程序获取和处理时间信息,是在 C 语言中进行时间操作的重要工具。
谢谢之前看这篇博文的粉丝,现在要稍微做一点修改,之前写的有点乱
time
头文件中的类型定义
主要的结构体如下。
struct tm
{
int tm_sec; // 秒 - [0, 60] including leap second
int tm_min; // 分钟 - [0, 59]
int tm_hour; // 时 - [0, 23]
int tm_mday; // 日期 - [1, 31]
int tm_mon; // 月份从0开始 - [0, 11]
int tm_year; // 当前时间减去1900
int tm_wday; // 星期 - [0, 6]
int tm_yday; // 从1月1号开始的日期 - [0, 365]
int tm_isdst; // 夏令时时间
};
两个简单的类型定义
time_t
用于处理时间点和时间间隔,通常用于日期和时间的操作。clock_t
用于测量程序执行的时钟周期数,用于性能分析和计时。
相关函数的作用
函数 | 作用 |
---|---|
time_t time(time_t *seconds) | 获取当前时间的 time_t 值,可通过 seconds 参数返回时间值(可选)。如果 seconds 为 NULL ,则将当前时间返回。 |
double difftime(time_t time1, time_t time2) | 计算两个时间之间的差值,返回以秒为单位的时间间隔。 |
struct tm *localtime(const time_t *timer) | 将 time_t 类型的时间转换为本地时间,并存储在 tm 结构体中。 |
struct tm *gmtime(const time_t *timer) | 将 time_t 类型的时间转换为 UTC 时间,并存储在 tm 结构体中。 |
char *ctime(const time_t *timer) | 根据给定的 time_t 值,返回一个表示时间的字符串,类似于 %c 格式符号。 |
size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr) | 根据指定的格式化规则 format ,将 tm 结构体中的时间转换为字符串,并存储在 str 中。 |
time_t mktime(struct tm *timeptr) | 将 tm 结构体中的时间转换为本地时区的 time_t 值。如果转换失败,返回 -1 。 |
char *asctime(const struct tm *timeptr) | 将 tm 结构体中的时间转换为字符串,并返回一个指向字符串的指针,类似于 ctime 函数。 |
clock_t clock(void) | 返回程序启动以来所使用的时钟周期数。如果失败,返回 -1 。 |
strftime的format参数介绍
格式化规则 | 含义 |
---|---|
%Y | 年份(4 位数字),小写y为后两位 |
%m | 月份(01-12) |
%d | 日期(01-31) |
%H | 小时(00-23) |
%M | 分钟(00-59) |
%S | 秒(00-59) |
%A | 星期全称(Sunday-Saturday) |
%a | 星期简称(Sun-Sat) |
%B | 月份全称(January-December) |
%b | 月份简称(Jan-Dec) |
%c | 日期和时间表示 |
%x | 日期表示 |
%X | 时间表示 |
%j | 一年中的天数(001-366) |
%U | 一年中的周数(以周日为起始) |
%W | 一年中的周数(以周一为起始) |
%Z | 时区的缩写名称 |
%% | 百分号(% ) |
简单示例
void test_time()
{
time_t now;
time(&now);
struct tm *local_time = localtime(&now);
char time_str[80];
strftime(time_str, 80, "%Y-%m-%d %H:%M:%S", local_time);
struct tm *gmt_time = gmtime(&now);
char gmt_str[80];
strftime(gmt_str, 80, "%Y-%m-%d %H:%M:%S", gmt_time);
printf("当前本地时间: %s\n", time_str);
printf("当前格林威治时间: %s\n", gmt_str);
double diff = difftime(now, mktime(local_time));
printf("本地时间和秒数表示的时间差: %f\n", diff);
char *ctime_str = ctime(&now);
printf("字符串表示的当前时间: %s", ctime_str);
char *asctime_str = asctime(local_time);
printf("asctime 函数返回的时间字符串: %s", asctime_str);
clock_t start = clock();
// 执行一些操作
clock_t end = clock();
printf("程序执行时间: %f 秒\n", (double)(end - start) / CLOCKS_PER_SEC);
}