【问题标题】:strptime does not works with timezone format specifierstrptime 不适用于时区格式说明符
【发布时间】:2016-04-26 12:47:03
【问题描述】:

我是 c 新手,正在尝试使用 strptime 函数,它将字符串时间转换为结构 tm。转换后我没有得到正确的时间。一切都很好,但年份显示错误(默认年份 1900)。

#include <stdio.h>
#include <time.h>
#include <string.h>
#include <ctype.h>

int main()
{
    struct tm tm;
    char *pszTemp = "Mon Apr 25 09:53:00 IST 2016";
    char szTempBuffer[256];

    memset(&tm, 0, sizeof(struct tm));
    memset(szTempBuffer, 0, sizeof(szTempBuffer));
    strptime(pszTemp, "%a %b %d %H:%M:%S %Z %Y", &tm);
    strftime(szTempBuffer, sizeof(szTempBuffer), "%Y-%m-%d %H:%M:%S", &tm);

    printf("Last Boot Time after parsed = %s\n", szTempBuffer);

    return 0;
}

输出:1900-04-25 09:53:00

【问题讨论】:

  • 您检查过strptime 返回的内容吗?这样它就不会返回NULL 指针?
  • 您是否尝试使用-Wall 选项进行编译?
  • @LPs:没用。
  • @JoachimPileborg:它返回 NULL。你能说出原因/解决方案吗??
  • 你的平台是什么?我在 debian 8.2 gcc 4.9 上试过,一切正常。

标签: c timezone unix-timestamp strptime


【解决方案1】:

正如您在time.h 源文件中看到的,您必须在包含time.h 之前声明__USE_XOPEN_GNU_SOURCE

#define __USE_XOPEN
#define _GNU_SOURCE

#include <stdio.h>
#include <time.h>
#include <string.h>
#include <ctype.h>

int main()
{
    struct tm tm;
    char *pszTemp = "Mon Apr 25 09:53:00 IST 2016";
    char szTempBuffer[256];

    memset(&tm, 0, sizeof(struct tm));
    memset(szTempBuffer, 0, sizeof(szTempBuffer));
    strptime(pszTemp, "%a %b %d %H:%M:%S %Z %Y", &tm);
    strftime(szTempBuffer, sizeof(szTempBuffer), "%Y-%m-%d %H:%M:%S", &tm);

    printf("Last Boot Time after parsed = %s\n", szTempBuffer);

    return 0;
}

您也可以简单地将定义添加到您的 gcc 命令中:

gcc -Wall test.c -o test -D__USE_XOPEN -D_GNU_SOURCE

编辑

This historical SO post 提供有关这些定义的所有信息。

【讨论】:

  • 您能解释一下为什么需要这样做吗?编辑:谢谢。
  • @2501 This historical SO post 提供有关这些定义的所有信息。
【解决方案2】:

%Z 不适用于 strptime,仅适用于 strftime。 strptime 在 %Z 之后停止读取。因此缺少 2016 年。

http://linux.die.net/man/3/strptime

如果你使用 glibc,它应该可以工作。

【讨论】:

  • 把%Z和2016的位置玩一下就可以看到了
猜你喜欢
  • 1970-01-01
  • 2011-10-08
  • 1970-01-01
  • 1970-01-01
  • 2018-03-13
  • 1970-01-01
  • 2016-02-13
  • 2013-08-28
  • 1970-01-01
相关资源
最近更新 更多