c/c++ strptime() 不解析 %Z 时区名称

2024-05-07

我是 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 正确解析时区名称的东西?

提前致谢,

Albert


我不确定你所做的事情是否有效。这glibc源代码 https://github.com/andikleen/glibc/blob/master/time/strptime_l.c在 github 上对此事有这样的说法:

case 'Z':
    /* XXX How to handle this? */
    break

接下来是对小写字母的一些稍微“充实”的处理'z'东西 :-)

所以这里最有可能发生的是字符串指针没有前进到超过EET当格式字符串为%Z,这样当它尝试处理时%Y,它抱怨,这是正确的,EET不是有效的年份。这个简单的案例证实了这一点"%%"代码实际上在哪里does推进输入字符串指针rp:

case '%':
    /* Match the `%' character itself.  */
    match_char ('%', *rp++);
    break;

Linux 手册页还说明了扩展(其中'Z'是一):

出于对称性的原因,glibc 尝试支持 strptime() 与 strftime(3) 相同的格式字符。 (大多数情况下会解析相应的字段,但 tm 中不会更改任何字段。)

除此之外GNU docs http://www.gnu.org/software/libc/manual/html_node/Low_002dLevel-Time-String-Parsing.html状态(我的斜体):

%Z:时区名称。注意:目前,这尚未完全实施。格式被识别,输入被消耗但 tm 中没有设置字段。

所以我实际上认为这是一个错误,尽管可以通过更改文档轻松修复该错误,以停止假装它可以处理Z- 类型时区。

我在 bugzilla 中找不到任何相关的错误,所以我在那里提出了 glibc 上的错误。你可以追踪它here http://sourceware.org/bugzilla/show_bug.cgi?id=14876.


附录:根据上一段中的错误报告链接和glibc 2.19 发布通知 https://sourceware.org/ml/libc-alpha/2014-02/msg00224.html,我建议的更改是为了使代码与文档保持一致。希望它没有错误,否则我会看起来很傻,因为它只有五行代码。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

c/c++ strptime() 不解析 %Z 时区名称 的相关文章

随机推荐