Question

I'm trying to calculate the date difference between two dates, using mktime and difftime. One of the dates is a struct tm inside another struct and the other date is a struct tm inside main. mktime works fine one the date inside main, but keeps returning -1 for the date inside the struct. I think I'm overlooking something pretty obvious on how to access a struct inside a struct but I couldn't find the answer. Thanks in advance.

The code is below

#include <stdio.h>
#include <time.h>

struct consulta_cand {
    struct tm nascimento;
};

int main(void)
{
    struct consulta_cand candidato;
    time_t now;
    struct tm final2012;
    double timeprint;

    now = time(NULL);
    final2012 = *localtime(&now);
    final2012.tm_mday = 28;
    final2012.tm_mon = 10 - 1;
    final2012.tm_year = 2012 - 1900;
    final2012.tm_hour = 23;
    final2012.tm_min = 59;
    final2012.tm_sec = 59;

    timeprint = mktime(&final2012);
    printf("%.f\n", timeprint);

    candidato.nascimento = *localtime(&now);
    candidato.nascimento.tm_mday = 14;
    candidato.nascimento.tm_mon = 10 - 1;
    candidato.nascimento.tm_year = 1967 - 1900;
    candidato.nascimento.tm_hour = 0;
    candidato.nascimento.tm_min = 0;
    candidato.nascimento.tm_sec = 0;

    timeprint = mktime(&candidato.nascimento);
    printf("%.f\n", timeprint);

    return 0;
}
Was it helpful?

Solution 3

There is no problem on the way the struct is accessed. The problem is the date before 1970 which mktime() doesn't accept.

OTHER TIPS

Are you sure it returns -1, but not simply a negative value, typical -69987600 which are the seconds from 1st January 1970 (back to) 14th October 1967?

That 1967 date is before Epoch time starts, so its Epoch representation is negativ.

These date functions are based on the epoch year: 1970. You're using a 1967 year.

As an aside: Dennis Ritchie wanted the epoch at 1970 so that the values (both negative and positive) would span his entire life. (Or so he once said in an interview.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top