如何在 C 语言中获取时间
获取时间是编程中一项常见任务,C 语言提供了几个函数来实现这一点。
1. time 函数
time函数返回当前时间自 1970 年 1 月 1 日以来的秒数。语法为:
立即学习“C语言免费学习笔记(深入)”;
<code class="c">time_t time(time_t *t);</code>
其中,
t是一个指针,用于存储返回的秒数。
2. localtime 函数
localtime函数将
time_t结构转换为
struct tm结构,其中包含时间和日期信息。语法为:
<code class="c">struct tm *localtime(const time_t *t);</code>
其中,
t是要转换的
time_t值。
3. strftime 函数
strftime函数将
struct tm结构格式化为字符串。语法为:
<code class="c">size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);</code>
其中:
s是输出字符串的缓冲区。
max是缓冲区的大小。
format是指定输出格式的格式字符串。
tm是要格式化的
struct tm结构。
格式字符串可以使用以下占位符:
| 占位符 | 描述 |
|---|---|
| %Y | 年份 |
| %m | 月份 |
| %d | 日期 |
| %H | 小时 (24 小时制) |
| %M | 分钟 |
| %S | 秒 |
示例
以下代码片段展示了如何使用这些函数获取和格式化当前时间:
<code class="c">#include <time.h>
#include <stdio.h>
int main() {
time_t t = time(NULL);
struct tm *tm = localtime(&t);
char buf[80];
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", tm);
printf("当前时间:%s\n", buf);
return 0;
}</code>输出:
<code>当前时间:2023-02-17 15:45:29</code>
