strptime不适用于时区格式说明符

时间:2016-04-26 12:47:04

标签: c timezone unix-timestamp strptime

我是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

2 个答案:

答案 0 :(得分:1)

正如您可以看到__USE_XOPEN源文件,您必须先声明_GNU_SOURCEtime.h才能加入#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 -Wall test.c -o test -D__USE_XOPEN -D_GNU_SOURCE

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

{{1}}

修改

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

答案 1 :(得分:0)

%Z不适用于strptime,仅适用于strftime。在%Z之后,strptime停止阅读。因此2016年不见了。

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

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