在Linux中,strftime
是一個用于格式化時間的函數
#include <stdio.h>
#include <time.h>
int main() {
time_t rawtime;
struct tm * timeinfo;
// 獲取當前時間
time(&rawtime);
// 將時間轉換為可讀格式
timeinfo = localtime(&rawtime);
// 使用strftime格式化時間
char buffer[80];
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeinfo);
// 輸出格式化后的時間
printf("Formatted time: %s\n", buffer);
return 0;
}
在這個示例中,我們首先使用time()
函數獲取當前時間(從1970年1月1日00:00:00 UTC開始的秒數),然后使用localtime()
函數將這個時間轉換為本地時間。接下來,我們使用strftime()
函數將本地時間格式化為一個字符串,最后輸出這個字符串。
strftime()
函數中的格式化字符串指定了我們希望輸出的時間格式。在這個例子中,我們使用了以下格式化指令:
%Y
:四位數的年份(例如:2022)%m
:月份(01到12)%d
:日期(01到31)%H
:小時(00到23)%M
:分鐘(00到59)%S
:秒(00到59)你可以根據需要修改這些格式化指令以獲得不同的時間格式。完整的格式化字符串可以參考strftime()文檔。