我正在尝试使用 strptime(buf, &pattern,&result)
转换 char[]
包含日期到 tm
结构。
我正在使用这样的函数:
if(strptime(buf, &pattern,&result) == NULL)
{
printf("\nstrptime failed\n");
...
如果我的变量定义如下,一切正常:
char buf[] = "26/10/2011";
char pattern[] = "%d/%m/%y";
struct tm result;
但是如果我把它们改成:
char buf[] = "2011/26/10";
char pattern[] = "%y/%d/%m";
struct tm result;
我得到“strptime 失败”。请注意,我只将年份放在开头(在 buf
和 pattern
中)。
感谢帮助。我的最终目标是以这种格式转换字符串:2011-10-26T08:39:21
最佳答案
这是因为小写的 %y
代表了本世纪内 的两位数年份。尝试将其更改为大写 %Y
,它会正常工作。您可以从以下程序中看到这一点:
#include <stdio.h>
#include <time.h>
int main (void) {
char buf[] = "26/10/2011";
char pattern[] = "%d/%m/%y";
struct tm result;
if (strptime (buf, pattern, &result) == NULL) {
printf("strptime failed\n");
return -1;
}
printf ("%d\n", 1900 + result.tm_year);
return 0;
}
这会输出 2020
,这意味着年份被读取为 2011
的 20
部分,其余部分将被忽略。如果您使用大写的 %Y
,它会输出正确的 2011
。
使用反转格式生成转换错误的代码:
#include <stdio.h>
#include <time.h>
int main (void) {
char buf[] = "2011/10/26";
char pattern[] = "%y/%m/%d";
struct tm result;
if (strptime (buf, pattern, &result) == NULL) {
printf("strptime failed\n");
return -1;
}
printf ("%d\n", 1900 + result.tm_year);
return 0;
}
当您将 pattern
值更改为 "%Y/%m/%d"
时,将正常工作(即输出 2011
) .
关于c - strptime 中元素的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7900006/