c语言time函数怎么用

2024-05-25 0 70

c 语言的 time 函数返回自 1970 年 1 月 1 日 00:00:00 utc 以来经过的秒数。用法:获取当前时间:time_t now = time(null);转换为特定时区:struct tm *local_time = localtime(&now);格式化为字符串:char buffer[100]; strftime(buffer, sizeof(buffer), “%y-%m-%d %h:%m:%s”, local_time);

c语言time函数怎么用

C 语言 time 函数的用法

简介

C 语言中的 time 函数可获取当前系统时间。它返回自 1970 年 1 月 1 日 00:00:00 UTC 以来经过的秒数。

语法

time_t time(time_t *t);

登录后复制

  • time_t t:可选参数,指向存储时间值的变量。

返回值

  • 如果成功,返回自 1970 年 1 月 1 日 00:00:00 UTC 以来经过的秒数。
  • 如果失败,返回 -1,并设置 errno 来指示错误。

用法

  1. 获取当前时间:

    time_t now = time(NULL);

    登录后复制

  2. 将时间转换为特定时区:

    struct tm *local_time = localtime(&now);

    登录后复制

  3. 将时间格式化为字符串:

    char buffer[100];
    strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local_time);

    登录后复制

示例

#include 
#include 

int main() {
    time_t now = time(NULL);
    if (now == -1) {
        perror("time() failed");
        return 1;
    }

    struct tm *local_time = localtime(&now);
    char buffer[100];
    strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local_time);

    printf("Current time: %sn", buffer);
    return 0;
}

登录后复制

输出:

Current time: 2023-03-08 12:34:56

登录后复制

以上就是c语言time函数怎么用的详细内容,更多请关注叮当号网其它相关文章!

相关文章

猜你喜欢