这是我的程序 time_play.c :
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int
main (void)
{
char *time_str = "2011-07-20 17:30:18";
time_t time_tm = getdate(time_str);
printf("str: %s and time: %s \n", time_str, ctime(&time_tm));
return 0;
}
它的输出:
$ gcc -o time_play time_play.c
$ ./time_play
str: 2011-07-20 17:30:18 and time: Wed Dec 31 16:00:00 1969
可以看出,time 的值为 NULL。为什么会这样?
最佳答案
您是否创建了一个模板文件来指定您正在使用的日期格式?
来自手册页:
User-supplied templates are used to parse and interpret the input string. The templates are text files created by the user and identified via the environment variable DATEMSK.
创建一个类似 timetemplate.txt 的文件:
%Y-%m-%d %H:%M:%S
然后设置DATEMSK的值指向它:
export DATEMSK=/home/somebody/timetemplate.txt
这段代码在 OS X 上对我有用,结合设置 DATEMSK:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main (void)
{
char *time_str = "2011-07-20 17:30:18";
struct tm *time_tm = getdate(time_str);
time_t t = mktime(time_tm);
printf("str: %s and time: %s", time_str, ctime(&t));
return 0;
}
关于c - getdate 和 ctime 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6780572/