在C語言中,time()
函數(shù)是用來獲取當(dāng)前日歷時(shí)間的
<time.h>
。time()
函數(shù)并將其返回值存儲(chǔ)在一個(gè)time_t
類型的變量中。localtime()
, strftime()
等)來格式化和顯示時(shí)間。下面是一個(gè)簡(jiǎn)單的示例程序,展示了如何在C語言中結(jié)合其他函數(shù)使用time()
:
#include<stdio.h>
#include <time.h>
int main() {
// 獲取當(dāng)前日歷時(shí)間
time_t currentTime = time(NULL);
// 將當(dāng)前時(shí)間轉(zhuǎn)換為本地時(shí)間
struct tm *localTime = localtime(¤tTime);
// 格式化時(shí)間字符串
char formattedTime[50];
strftime(formattedTime, sizeof(formattedTime), "%Y-%m-%d %H:%M:%S", localTime);
// 打印格式化后的時(shí)間
printf("當(dāng)前時(shí)間: %s\n", formattedTime);
return 0;
}
這個(gè)程序會(huì)輸出當(dāng)前的日期和時(shí)間,例如:
當(dāng)前時(shí)間: 2022-06-29 14:45:30
在這個(gè)示例中,我們首先使用time()
函數(shù)獲取當(dāng)前日歷時(shí)間,并將其存儲(chǔ)在currentTime
變量中。然后,我們使用localtime()
函數(shù)將currentTime
轉(zhuǎn)換為本地時(shí)間,并將結(jié)果存儲(chǔ)在localTime
指針中。接下來,我們使用strftime()
函數(shù)將localTime
格式化為一個(gè)易讀的字符串,并將結(jié)果存儲(chǔ)在formattedTime
數(shù)組中。最后,我們使用printf()
函數(shù)打印格式化后的時(shí)間。