温馨提示×

c语言如何获取系统时间

小亿
249
2024-03-22 20:14:55
栏目: 编程语言

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

  1. 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; } 
  1. 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; } 
  1. 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语言中获取系统时间,并进行相应的操作。

0