C 语言中获取和输出当前时间164


在 C 语言中,我们可以使用 头文件中的函数来获取和输出当前时间。这些函数提供了灵活的方式来处理各种时间值并将其转换为可读格式。

获取当前时间

ctime 函数


ctime 函数将当前时间转换为一个可读字符串。其语法如下:```c
char *ctime(const time_t *timeptr);
```

其中,timeptr 指向一个存储时间值(自 Epoch 以来经过的秒数)的变量。ctime 函数返回一个指向可读字符串的指针,该字符串包含以下格式的时间:```
Day Mon dd hh:mm:ss yyyy
```

例如:```c
#include
int main() {
time_t now = time(NULL);
char *time_str = ctime(&now);
printf("当前时间:%s", time_str);
return 0;
}
```
输出:
```
当前时间:Sat Oct 01 15:23:45 2022
```

time 函数


time 函数获取当前时间并将其作为自 Epoch 以来经过的秒数返回。其语法如下:```c
time_t time(time_t *timeptr);
```

如果 timeptr 不为 NULL,则 time 函数将当前时间存储在 *timeptr 中。

例如:```c
#include
int main() {
time_t now = time(NULL);
printf("当前时间,自 Epoch 以来经过的秒数:%ld", now);
return 0;
}
```
输出:
```
当前时间,自 Epoch 以来经过的秒数:1664455025
```

输出格式化时间

strftime 函数


strftime 函数将当前时间格式化为指定格式字符串。其语法如下:```c
size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr);
```

其中:* str 指向存储格式化时间的缓冲区。
* maxsize 是缓冲区的最大大小。
* format 是指定时间格式的格式字符串。
* timeptr 指向一个 struct tm 结构,其中包含当前时间值。

我们可以使用 localtime 函数或 gmtime 函数将当前时间转换为 struct tm 结构。localtime 函数返回本地时间,而 gmtime 函数返回格林威治时间 (GMT)。

以下是格式化时间的一些常用格式说明符:| 说明符 | 输出 |
|---|---|
| %a | 星期中的缩写名称 |
| %A | 星期中的完整名称 |
| %b | 月份的缩写名称 |
| %B | 月份的完整名称 |
| %c | 本地化的日期和时间 |
| %d | 月中的天数 (01-31) |
| %H | 小时 (00-23) |
| %I | 小时 (12 小时制) (01-12) |
| %j | 一年中的第几天 (001-366) |
| %m | 月份号 (01-12) |
| %M | 分钟 (00-59) |
| %p | AM 或 PM |
| %S | 秒 (00-59) |
| %Y | 年份 (完整值) |

例如:```c
#include
#include
int main() {
time_t now = time(NULL);
struct tm *timeinfo = localtime(&now);
char buffer[80];
strftime(buffer, sizeof(buffer), "%A, %B %d, %Y %H:%M:%S", timeinfo);
printf("格式化的时间:%s", buffer);
return 0;
}
```
输出:
```
格式化的时间:星期六, 十月 1, 2022 15:23:45
```

2024-11-01


上一篇:C 语言文件函数调用

下一篇:C 语言中函数调用的全面指南