问题
Consider this program:
#include <stdio.h>
#include <time.h>
int main() {
struct tm t;
strptime("2015-08-13 12:00:00", "%F %T", &t);
printf("t.tm_wday = %d\n", t.tm_wday);
return 0;
}
Under OSX, this is what I obtain:
$ gcc test_strptime.c
$ ./a.out
t.tm_wday = 0
But on Linux, this is what I get:
$ gcc test_strptime.c
$ ./a.out
t.tm_wday = 4
Why is the bahaviour different? I would expect the day of the week to be well defined, given the data and the time of the day?
回答1:
The Linux (glibc) and OS X implementations of strptime
are different. From the OS X man page:
If the format string does not contain enough conversion specifications to completely specify the resulting
struct tm
, the unspecified members of tm are left untouched. For example, if format is ``%H:%M:%S'', onlytm_hour
,tm_sec
andtm_min
will be modified.
Compared with glibc:
The glibc implementation does not touch those fields which are not explicitly specified, except that it recomputes the
tm_wday
andtm_yday
field if any of the year, month, or day elements changed.
So, you could say it's working as documented.
来源:https://stackoverflow.com/questions/31984002/why-does-strptime-behave-differently-on-osx-and-on-linux