我得到一个 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/