TheMachineX
TheMachineX

Reputation: 209

Converting time_t to a DATE struct in c

I have the following struct:

typedef struct Date {
   short day, month, year;
} DATE;

I want to create a function that gets a time_t variable and convert it to DATE but I am having some issues with it. Tried the following:

DATE timeTConverter(time_t date) 
{
    struct tm *giverTime;
    giverTime = localtime(date);
    DATE given;
    given.day = giverTime->tm_mday;
    given.month = giverTime->tm_mon++;
    given.year = giverTime->tm_year;

    return given;
}

But it doesn't seem to work. Any ideas?

Upvotes: 0

Views: 1278

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

localtime() takes a pointer to time_t, not time_t itself.

Also incrementing giverTime->tm_mon doesn't make sense because the result is not used. It seems you wanted to assign giverTime->tm_mon + 1 instead.

DATE timeTConverter(time_t date) 
{
    struct tm *giverTime;
    giverTime = localtime(&date); /* pass a pointer */
    DATE given;
    given.day = giverTime->tm_mday;
    given.month = giverTime->tm_mon+1; /* simply add instead of increment */
    given.year = giverTime->tm_year;

    return given;
}

Upvotes: 5

Related Questions