Ravi Bhushan
Ravi Bhushan

Reputation: 253

strptime does not works with timezone format specifier

I am new to c and trying out on strptime function, which converts string time to structure tm. After converting i am not getting right time. everything is fine but year is displaying wrong(default year 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;
}

Output : 1900-04-25 09:53:00

Upvotes: 0

Views: 975

Answers (2)

LPs
LPs

Reputation: 16233

As you can see into time.h source file you have to declare __USE_XOPEN and _GNU_SOURCE before to include time.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;
}

You can also simply add definition into you gcc command:

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

EDIT

This historical SO post gives all infos about those defines.

Upvotes: 1

kbnl83
kbnl83

Reputation: 1

The %Z doesn't work for strptime, only for strftime. strptime stops reading after %Z. Therefore the 2016 is missing.

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

If you use glibc it should work.

Upvotes: 0

Related Questions