time_t time(time_t *t);其中,t 是一个指针,用于存储返回的秒数。2. localtime 函数loc">

c语言如何获取时间

来源:这里教程网 时间:2026-02-21 16:49:21 作者:

如何在 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>

相关推荐