c语言如何获取当前时间

983
2023/12/11 14:46:33
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C语言中,可以使用time.h头文件中的函数来获取当前时间。

可以使用time函数获取当前的系统时间,time函数返回的是从1970年1月1日零时到当前时间的秒数(即时间戳)。示例如下:

#include <stdio.h>
#include <time.h>

int main() {
    time_t now;
    time(&now);
    printf("当前时间的时间戳:%ld\n", now);
    
    return 0;
}

输出结果类似于:

当前时间的时间戳:1621897336

如果想要将时间戳转换为本地时间,可以使用localtime函数。示例如下:

#include <stdio.h>
#include <time.h>

int main() {
    time_t now;
    struct tm *t;
    time(&now);
    t = localtime(&now);
    printf("当前本地时间:%d-%d-%d %d:%d:%d\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
    
    return 0;
}

输出结果类似于:

当前本地时间:2021-5-25 10:17:16

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c语言累加求和代码怎么写