【问题标题】:How to print time_t in a specific format?如何以特定格式打印 time_t?
【发布时间】:2013-08-24 19:37:03
【问题描述】:

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

Aug 23 06:07 

如何将来自stat()mtime() 的时间转换为这种格式的当地时间?

【问题讨论】:

标签: c linux time timezone ls


【解决方案1】:

使用strftime(需要先将time_t转换为struct tm*):

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

格式:

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

这里是完整的代码:

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

【讨论】:

  • 然后使用printf("%s",buff);?
  • 完全正确 - 它将用可打印的字符串填充 buff 数组。
  • 不熟悉不同的时间数据类型。你能告诉stat()应该是什么步骤
  • 嗯 - time_t 包含自 1970 年 1 月 1 日 00:00 UTC 以来经过的秒数。 struct tm 包含分解成其组件的日历日期和时间。
  • 不,你不能通过mtime。您需要将info.st_mtime 传递给本地时间函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 2013-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多