hari
hari

Reputation: 9733

getdate and ctime not working properly

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?

Upvotes: 2

Views: 2743

Answers (3)

Jinnan
Jinnan

Reputation: 25

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

Upvotes: 0

Mike
Mike

Reputation: 964

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;
}

Upvotes: 2

mu is too short
mu is too short

Reputation: 434606

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.

Upvotes: 1

Related Questions