How to print time_t in a specific format?

China☆狼群 提交于 2019-11-27 18:19:25

问题


ls command prints time in this format:

Aug 23 06:07 

How can I convert time received from stat()'s mtime() into this format for local time?


回答1:


Use strftime (you need to convert time_t to struct tm* first):

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

Formats:

%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).

Here is the full code:

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);


来源:https://stackoverflow.com/questions/18422384/how-to-print-time-t-in-a-specific-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!