如何从 struct tm 中生成人类可读的字符串? [英] How do I make a human-readable string out of a struct tm?

查看:27
本文介绍了如何从 struct tm 中生成人类可读的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个 struct tm 并且我想将它转换成一个带有这个特定输出的字符串:

I am getting a struct tm and I want to convert it into a string with this specific output:

dd-mm-yyyy hh:mm

dd-mm-yyyy hh:mm

除月份(mm)外,所有内容都是数字,例如:

where everything is a number except for the month (mm), such as:

2010 年 10 月 14 日 10:35

14-Oct-2010 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),还是有更好的解决方案?

The issue is that I don't know how I could transfer this pmytm->tm_mon into the month efficiently. Do you recommend that I build an array of months and just index into that array (replacing %d with %s in my sprintf), or is there a better solution please?

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

Also, I have an issue with the hours and minutes. If it is below 10 (2 numbers), it will display only one number such as: 10:8 rather than 10:08. How can I please fix that?

非常感谢您的帮助,

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

What I have in mind as a solution (is that elegant ?):

  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

Use the function strftime from time.h

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

这篇关于如何从 struct tm 中生成人类可读的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆