Pergunta

I am reading a json in a C program. I receive a string like this:

Apr 3, 2014 4:44:39 PM

I am parsing it with strptime to get all values like this:

strptime(observationDate, "%b %d, %Y %H:%M:%S %p", &result);

I tried also with %r instead of %p. In observationDate I have the string containing the date in string format. result is a struct tm.

But, even getting PM in the first string, when I try to print the date after conversion I get 4 instead of 16.I print like this, debugLog is a function to print the system date before text...

debugLog(DEB_INFO, "observationDateConverted: %d-%d-%d %d:%d:%d\n", 
                    result.tm_year+1900, 
                    result.tm_mon + 1, 
                    result.tm_mday, 
                    result.tm_hour, 
                    result.tm_min, 
                    result.tm_sec);
Foi útil?

Solução

Either use %r or %I:%M:%S %p (note it's I not H).

From man strptime (emphasis by me):

%r
The 12-hour clock time (using the locale's AM or PM). In the POSIX locale equivalent to %I:%M:%S %p.

The lesson learned here: RTFM!

Test program:

#define _XOPEN_SOURCE

#include <time.h>

const char d[] = "Apr 3, 2014 4:44:39 PM";

int main(void)
{
  struct tm t = { 0 };

  strptime(d, "%b %d, %Y %I:%M:%S %p", &t);
}

Checking the result:

$gdb ./main
[...]
b 12
r
Breakpoint 1, main () at main.c:12
12  }
(gdb) p t
$2 = {tm_sec = 39, tm_min = 44, tm_hour = 16, tm_mday = 3, tm_mon = 3, tm_year = 114, tm_wday = 4, tm_yday = 92, tm_isdst = 0, __tm_gmtoff = 0, __tm_zone = 0x0}
(gdb) 
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top