c - 如何从 struct tm 中生成人类可读的字符串?

标签 c time

我得到一个 struct tm,我想将它转换成一个字符串,输出如下:

dd-mm-yyyy hh:mm

其中除月份 (mm) 外的所有内容均为数字,例如:

2010 年 10 月 14 日 10:35

这是我当前的代码:

  struct stat sb;
  if (lstat(path, &sb) == 0) {
    struct tm *pmytm = gmtime(&sb.st_mtime);
    sprintf(array[index]->mtime, "%d-%d-%d %d:%d", pmytm->tm_mday, pmytm->tm_mon, 1900 + pmytm->tm_year, pmytm->tm_hour, pmytm->tm_min);

问题是我不知道如何有效地将这个 pmytm->tm_mon 转移到月份中。您是否建议我构建一个月份数组并仅对该数组进行索引(在我的 sprintf 中将 %d 替换为 %s),还是有更好的解决方案?

此外,我对小时和分钟有疑问。如果小于 10(2 个数字),它将只显示一个数字,例如:10:8 而不是 10:08。我该如何解决这个问题?

非常感谢您的帮助,

编辑:我想到的解决方案(优雅吗?):

  static char *months[] = { "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

  struct stat sb;
  if (lstat(path, &sb) == 0) {
    struct tm *pmytm = gmtime(&sb.st_mtime);
    sprintf(array[index]->mtime, "%02d-%s-%d %02d:%02d", pmytm->tm_mday, months[pmytm->tm_mon], 1900 + pmytm->tm_year, pmytm->tm_hour, pmytm->tm_min);

贾里

最佳答案

使用time.h中的函数strftime

strftime(array[index]->mtime, 20, "%d-%b-%Y %H:%M", pmytm);

关于c - 如何从 struct tm 中生成人类可读的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3937301/

相关文章:

sql - 在 SQL 中显示时间

c - 内核编程 : wait queue uses spinlock internally

c++ - 以下函数的时间复杂度应该是多少?

c - 数列长度、数组中元素的第一个和最后一个索引

c++ - longjmp 应该恢复堆栈吗?

mysql - 如何在 grails 域中捕获毫秒

Python:从 strftime 打印时区

javascript - 如何使用 jQuery 以秒为单位获取两个时间戳之间的时差?

C语言中的子父关系和继承

c - 有没有办法在 C 中使用/调用 COM 接口(interface)?