您的位置:宽带测速网 > 编程知识 > c语言如何获取系统时间

c语言如何获取系统时间

2025-06-21 20:40来源:互联网 [ ]

要在C语言中获取系统时间,可以使用 <time.h> 头文件中的函数。以下是一些获取系统时间的常用函数:

    time() 函数:返回当前时间(从1970年1月1日开始的秒数)。
#include <stdio.h>#include <time.h>int main() {time_t currentTime;time(&currentTime);printf("Current time: %ld\n", currentTime);return 0;}
    ctime() 函数:将时间(从1970年1月1日开始的秒数)转换成字符串形式。
#include <stdio.h>#include <time.h>int main() {time_t currentTime;time(&currentTime);printf("Current time: %s", ctime(&currentTime));return 0;}
    gmtime() 函数:将时间(从1970年1月1日开始的秒数)转换成 struct tm 结构体,表示UTC时间。
#include <stdio.h>#include <time.h>int main() {time_t currentTime;struct tm *timeinfo;time(&currentTime);timeinfo = gmtime(&currentTime);printf("Current UTC time: %d-%d-%d %d:%d:%d\n", timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);return 0;}

这些函数可以帮助你在C语言中获取系统时间,并进行相应的操作。