我是C的新手。当我练习C来转换时间来刺激来回构造tm时。我注意到了一些差异。请告知我做错了什么。
#include <string.h>
#include <stdio.h>
#include <time.h>
/*
test different format string to strptime
" %A, %b %d, %X %z %Y "
" %A, %b %d, %X %Z %Y "
*/
int main(int argc,char *argv[])
{
char date[] = "6 Mar 2001 12:33:45";
char fmt[80];
struct tm tm;
if (argc==1) return 0;
strcpy(fmt,argv[1]);
memset(&tm, 0, sizeof(struct tm));
if (strptime(date,"%d %b %Y %H:%M:%S",&tm)==NULL) printf("error\n");
char buf[128];
strftime(buf, sizeof(buf), fmt, &tm);
printf("%s\n", buf);
printf("%d\n", tm.tm_isdst);
if (strptime(buf,fmt,&tm)==NULL) printf("error\n");
else {
printf("year: %d; month: %d; day: %d;\n",
tm.tm_year, tm.tm_mon, tm.tm_mday);
printf("hour: %d; minute: %d; second: %d\n",
tm.tm_hour, tm.tm_min, tm.tm_sec);
printf("week day: %d; year day: %d\n", tm.tm_wday, tm.tm_yday);
}
return 0;
}
当我使用“%A,%b%d,%X%z%Y”作为转换格式参数时,代码提供了如下结果:
~/user$ ./test_time " %A, %b %d, %X %z %Y "
Tuesday, Mar 06, 12:33:45 +0000 2001
0
year: 101; month: 2; day: 6;
hour: 12; minute: 33; second: 45
week day: 2; year day: 64
当我将参数更改为“%A,%b%d,%X%Z%Y”时,代码无法解析strftime生成的时间字符串格式完全相同。
~/user$ ./test_time " %A, %b %d, %X %Z %Y "
Tuesday, Mar 06, 12:33:45 EET 2001
0
error
我是否错过了让strptime正确解析时区名称的内容?
提前致谢,
阿尔伯特
答案 0 :(得分:9)
我不确定你在做什么会起作用。 github上的glibc source code就此问题说了这句话:
case 'Z':
/* XXX How to handle this? */
break
然后对小写'z'
内容进行一些稍微“多余”处理: - )
所以最有可能发生的事情是,当格式字符串为EET
时,字符串指针没有超过%Z
,因此当它尝试处理%Y
时,它抱怨,这是正确的,EET
不是有效的一年。 "%%"
的简单情况证实了这一点,其中代码实际上 推进输入字符串指针rp
:
case '%':
/* Match the `%' character itself. */
match_char ('%', *rp++);
break;
Linux手册页还说明了扩展名(其中'Z'
是一个):
出于对称的原因,glibc试图支持strptime()与strftime(3)相同的格式字符。 (在大多数情况下,会解析相应的字段,但不会更改tm中的字段。)
另外GNU docs状态(我的斜体):
%Z:时区名称。注意:目前,这还没有完全实现。识别格式,消耗输入但未设置tm中的字段。
所以我实际上认为这是一个错误,虽然可以通过文档更改轻松修复,以阻止它假装它可以处理Z
- 类型时区。
我在bugzilla中找不到任何相关的bug,所以我在glibc上提出了一个bug。您可以跟踪here。
附录:根据前一段中的错误报告链接和glibc 2.19 release notice,我建议的更改是为了使代码与文档保持一致。希望它没有错误或者我看起来很傻,因为它只有五行代码。