Linux 如何以特定格式打印time_t?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18422384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:39:08 来源:igfitidea点击:
How to print time_t in a specific format?
提问by kBisla
ls command prints time in this format:
ls 命令以这种格式打印时间:
Aug 23 06:07
How can I convert time received from stat()
's mtime()
into this format for local time?
如何将从stat()
's接收到的mtime()
时间转换为本地时间的这种格式?
采纳答案by Nemanja Boric
Use strftime(you need to convert time_t
to struct tm*
first):
使用strftime(您需要先转换time_t
为struct tm*
):
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);