[英]How do I make a human-readable string out of a struct tm?
I am getting a struct tm and I want to convert it into a string with this specific output: 我正在获取一个struct tm,我想将其转换为具有以下特定输出的字符串:
dd-mm-yyyy hh:mm dd-mm-yyyy hh:mm
where everything is a number except for the month (mm), such as: 其中除月份(mm)以外的所有数字都是数字,例如:
14-Oct-2010 10:35 2010年10月14日10:35
This is my current code: 这是我当前的代码:
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);
The issue is that I don't know how I could transfer this pmytm->tm_mon into the month efficiently. 问题是我不知道如何有效地将此pmytm-> tm_mon转移到月份中。 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?
您是否建议我建立一个数月的数组并仅对该数组建立索引(将sprintf中的%d替换为%s),还是有更好的解决方案?
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.
如果小于10(2个数字),它将仅显示一个数字,例如:10:8而不是10:08。 How can I please fix that?
我该如何解决?
Thank you very much for your help, 非常感谢您的帮助,
EDIT: 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);
Jary 杰瑞
从time.h开始使用功能strftime
strftime(array[index]->mtime, 20, "%d-%b-%Y %H:%M", pmytm);
If you want more control of time formatting try using strfime: 如果要更多地控制时间格式,请尝试使用strfime:
struct stat sb;
if (lstat("/etc/passwd", &sb) == 0) {
char time_buf[256];
(void) strftime(time_buf, sizeof (time_buf),
"%m-%d-%Y %H-%M (mon=%b)", localtime(&sb.st_mtime));
(void) printf("Time: %s\n", time_buf);
}
You can use gmtime() instead of localtime() if you do not want timezone correction. 如果您不希望进行时区校正,则可以使用gmtime()代替localtime()。
The output from this is: 输出是:
Time: 08-30-2010 17-13 (mon=Aug)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.