考虑以下程序:
#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;
}
在OSX下,这是我获得的:
$gcc test_strptime.c
$./a.out
t.tm_wday = 0
但是在Linux上,这是我得到的:
$gcc test_strptime.c
$./a.out
t.tm_wday = 4
行为为何不同?考虑到数据和一天中的时间,我希望星期几能够得到很好的定义?
解决方法:
strptime的Linux(glibc)和OS X实现不同.从OS X man page开始:
If the format string does not contain enough conversion specifications to completely specify the
resultingstruct 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.
与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.
因此,您可以说它按文档所述工作.