如何以特定格式打印time_t?

kBi*_*sla 7 c linux time timezone ls

ls命令以这种格式打印时间:

Aug 23 06:07 
Run Code Online (Sandbox Code Playgroud)

我如何转换,从接收到的时间stat()mtime()这个格式的本地时间?

Nem*_*ric 12

使用strftime(你需要转换time_tstruct tm*第一个):

char buff[20];
struct tm * timeinfo;
timeinfo = localtime (&mtime);
strftime(buff, sizeof(buff), "%b %d %H:%M", timeinfo);
Run Code Online (Sandbox Code Playgroud)

格式:

%b - The abbreviated month name according to the current locale.

%d - The day of the month as a decimal number (range 01 to 31).

%H - The hour as a decimal number using a 24-hour clock (range 00 to 23).

%M - The minute as a decimal number (range 00 to 59).
Run Code Online (Sandbox Code Playgroud)

这是完整的代码:

struct stat info; 
char buff[20]; 
struct tm * timeinfo;

stat(workingFile, &info); 

timeinfo = localtime (&(info.st_mtime)); 
strftime(buff, 20, "%b %d %H:%M", timeinfo); 
printf("%s",buff);
Run Code Online (Sandbox Code Playgroud)

  • 好吧 - time_t 包含自 1970 年 1 月 1 日 UTC 时间 00:00 以来经过的秒数。`struct tm` 包含一个分解成其组件的日历日期和时间。 (2认同)