getdate 和 ctime 无法正常工作
这是我的程序 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。为什么会这样呢?
Here is my program 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;
}
And it's output:
$ 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
It can be seen that time is getting value NULL. Why is it so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否创建了指定您正在使用的日期格式的模板文件?
从手册页:
创建一个类似 timetemplate.txt 的文件:
然后将 DATEMSK 的值设置为指向它:
这段代码在 OS X 上适用于我,结合设置 DATEMSK:
Did you create a template file specifying the date format you are using?
From the man page:
Create a file like timetemplate.txt:
Then set the value of DATEMSK to point to it:
This code worked for me on OS X, in combination with setting the DATEMSK:
来自精细手册:
getdate
函数返回struct tm *
,而不是time_t
>。你很幸运,你的程序没有崩溃并着火。请为您的编译器打开更多警告标志,您应该看到如下内容:
对第 9 行进行强制转换。
From the fine manual:
The
getdate
function returns astruct tm *
, not atime_t
. You're lucky that your program isn't falling over and catching on fire.Please turn on more warning flags for your compiler, you should have seen something like this:
about line 9.
在 openSUSE 13.2 中,
必须在第一行添加以下代码:
#define _XOPEN_SOURCE 500
glibc 的功能测试宏要求(请参阅 feature_test_macros(7)):
man 3 getdate 它会告诉您:
glibc 的功能测试宏要求(请参阅 feature_test_macros( 7)):
In openSUSE 13.2,
MUST ADD the following code at the first line :
#define _XOPEN_SOURCE 500
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
man 3 getdate it will tell you:
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):