c - strptime 中元素的顺序

标签 c time.h

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

感谢帮助。我的最终目标是以这种格式转换字符串: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,这意味着年份被读取为 201120 部分,其余部分将被忽略。如果您使用大写的 %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/

相关文章:

无法弄清楚发生了什么 - C

c - select() 无法正常工作,错误在哪里?

c - GMP GNU 代码有错误?

C - 在结构 [time.h] 中存储 time_t 变量时出错

c - 使用 clock() 的延迟函数

c - 从 C 中的函数返回元组

c - MPI c 中的互通器

linux - 如何构建(获取/下载)time.h 库?

c - 如何在用户将两个字符作为输入插入时测量两个字符之间的时间(以秒为单位)

c - tm 结构(来自 time.h)如何工作?