0

我正在尝试使用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 失败”。请注意,我只将 year 放在开头(在buf和中pattern)。

帮助表示赞赏。我的最终目标是以这种格式转换字符串:2011-10-26T08:39:21

4

2 回答 2

3

这是因为小写是本世纪%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,这意味着年份仅被读取为 的20一部分2011,其余部分被忽略。如果您使用 upper-case %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;
}

2011当您将pattern值更改为"%Y/%m/%d".

于 2011-10-26T08:01:03.083 回答
0

使用我自己的“strptime”和“timestamp”命令,我得到:

$ strptime -T '%y/%d/%m' 2011/26/11
strptime: failed to convert <2011/26/11> using format <%y/%d/%m>
$ strptime -T '%Y/%d/%m' 2011/26/11
1322294400 = 2011/26/11
$ strptime -T '%d/%m/%y' 26/11/2011
1606377600 = 26/11/2011
$ timestamp 1322294400 1606377600
1322294400 = Sat Nov 26 00:00:00 2011
1606377600 = Thu Nov 26 00:00:00 2020
$

(这里的时区是美国/太平洋,目前是 UTC-7。)

请注意,该'%d/%m/%y'格式生成的日期是 2020 年,而不是 2011 年。

于 2011-10-26T08:08:19.433 回答