在Linux中,gettimeofday
函數用于獲取當前系統時間,它返回一個timeval
結構體,包含兩個成員:tv_sec
表示秒數,tv_usec
表示微秒數
#include <stdio.h>
#include <sys/time.h>
int main() {
struct timeval currentTime;
// 獲取當前時間
gettimeofday(¤tTime, NULL);
// 將時間轉換為字符串格式(例如:"YYYY-MM-DD HH:MM:SS")
char currentTimeStr[20];
strftime(currentTimeStr, sizeof(currentTimeStr), "%Y-%m-%d %H:%M:%S", localtime(¤tTime.tv_sec));
printf("當前時間:%s\n", currentTimeStr);
return 0;
}
在這個示例中,我們首先使用gettimeofday
函數獲取當前時間,然后使用localtime
函數將秒數轉換為本地時間結構體,最后使用strftime
函數將時間結構體轉換為字符串格式并打印出來。