C 语言系统时间函数:深入解析135


C 语言提供了广泛的函数库,用于与系统时间交互。这些函数对于各种应用程序至关重要,包括调度、日志记录和性能测量。## 1. time 函数

time 函数返回系统自纪元以来的秒数。纪元是 1970 年 1 月 1 日午夜 00:00:00 UTC。time 函数的原型如下:```c
time_t time(time_t *timer);
```

如果 timer 参数不为 NULL,则 time 函数将返回系统时间并将其存储在 timer 指向的内存位置。## 2. ctime 函数

ctime 函数将 time 函数返回的时间转换为可读的字符串。字符串采用以下格式:```
Day Month Date Time Year
```

例如,对于 2023 年 2 月 1 日中午 12:00:00 UTC,ctime 函数将返回以下字符串:```
Wed Feb 1 12:00:00 2023
```

ctime 函数的原型如下:```c
char *ctime(const time_t *timer);
```
## 3. localtime 函数

localtime 函数将 time 函数返回的时间转换为本地时间结构。本地时间结构包含有关日期和时间的各种信息,例如年、月、日、小时、分钟和秒。localtime 函数的原型如下:```c
struct tm *localtime(const time_t *timer);
```

struct tm 结构的定义如下:```c
struct tm {
int tm_sec; // 秒
int tm_min; // 分钟
int tm_hour; // 小时
int tm_mday; // 月中的天数
int tm_mon; // 月份(从 0 开始)
int tm_year; // 年份(从 1900 年开始)
int tm_wday; // 星期(从 0 开始,即星期日)
int tm_yday; // 年中的天数
int tm_isdst; // 夏令时标志
};
```
## 4. gmtime 函数

gmtime 函数与 localtime 函数类似,但它返回世界协调时间 (UTC) 时间结构。gmtime 函数的原型如下:```c
struct tm *gmtime(const time_t *timer);
```
## 5. strftime 函数

strftime 函数将本地时间结构或世界协调时间结构转换为可读的字符串。strftime 函数允许您指定字符串的格式,包括日期、时间、时区信息等。strftime 函数的原型如下:```c
size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr);
```

format 参数是一个格式化字符串,指定了输出字符串的格式。一些常用的格式化说明符如下:```
%a 缩写的星期名
%A 完整的星期名
%b 缩写的月份名
%B 完整的月份名
%c 本地化的日期和时间
%d 月中的天数(01 到 31)
%H 小时(00 到 23)
%I 小时(01 到 12)
%m 月份(01 到 12)
%M 分钟(00 到 59)
%p AM 或 PM
%S 秒(00 到 59)
%Y 年(例如,2023)
```
## 6. mktime 函数

mktime 函数将本地时间结构或世界协调时间结构转换为系统自纪元以来的秒数。mktime 函数的原型如下:```c
time_t mktime(struct tm *timeptr);
```
## 7. asctime 函数

asctime 函数是 ctime 函数的旧版本。它将 time 函数返回的时间转换为可读的字符串。asctime 函数的原型如下:```c
char *asctime(const struct tm *timeptr);
```
## 8. 其他函数

除了上述函数外,C 语言还提供了几个其他与系统时间相关的函数,包括:* clock 函数:返回程序运行的 CPU 时间。
* difftime 函数:計算兩個 time_t 之间的差值。

2024-12-05


上一篇:理解 C 语言中字符相反数

下一篇:如何使用 C 语言实现金额转换函数