c - getdate 和 ctime 无法正常工作

标签 c time ctime getdate

这是我的程序 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/

相关文章:

c++ - 处理夏令时 - C++

c - 如何将 C 函数公开给自定义虚拟机?

c - 链接和调用两个独立的电源

php - 将字符串转换为 UNIX 时间戳

c++ - <time.h>/<ctime> 不计算滴答

c++ - 以毫秒为单位的系统时间 C++

c - fscanf() 接受输入

c - 将用户输入的字符分配给变量

PHP获取本地日期和时间

C++、mingw 和 clock_gettime 无法编译