2

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?

hari
  • 9,439
  • 27
  • 76
  • 110
  • What platform are you on? The prototype I have for `getdate` is `struct tm *getdate(const char *string);`. – cdhowie Jul 21 '11 at 18:07

3 Answers3

2

Did you create a template file specifying the date format you are using?

From the man page:

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.

Create a file like timetemplate.txt:

%Y-%m-%d %H:%M:%S

Then set the value of DATEMSK to point to it:

export DATEMSK=/home/somebody/timetemplate.txt

This code worked for me on OS X, in combination with setting the 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;
}
Mike
  • 964
  • 9
  • 9
1

From the fine manual:

struct tm *getdate(const char *string);

The getdate function returns a struct tm *, not a time_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:

warning: initialization makes integer from pointer without a cast

about line 9.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
0

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)):

   getdate():
       _XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED
   getdate_r():
       _GNU_SOURCE

man 3 getdate it will tell you:

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

   getdate():
       _XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED
   getdate_r():
       _GNU_SOURCE
Community
  • 1
  • 1
Jinnan
  • 25
  • 5