0

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

LPs
  • 16,045
  • 8
  • 30
  • 61
Ravi Bhushan
  • 253
  • 3
  • 17

2 Answers2

1

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.

Community
  • 1
  • 1
LPs
  • 16,045
  • 8
  • 30
  • 61
  • 1
    Can you explain why is that necessary? Edit: Thank you. – 2501 Apr 26 '16 at 13:09
  • @2501 [This historical SO post](http://stackoverflow.com/questions/5378778/what-does-d-xopen-source-do-mean) gives all infos about those defines. – LPs Apr 26 '16 at 13:11
0

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.

kbnl83
  • 1
  • 1