How to calculate difference between dates using the time.h library

0

I saw that it has a function in time.h that calculates the difference between date I went to documentation link time.h , I did not quite understand how to perform this calculation, for example I wanted to calculate the difference between the date 12/09/2018 and 12/09/1997

Code that the page provided

#include <stdio.h>      /* printf */
#include <time.h>       /* time_t, struct tm, difftime, time, mktime */

int main ()
{
  time_t now;
  struct tm newyear;
  double seconds;

  time(&now);  /* get current time; same as: now = time(NULL)  */

  newyear = *localtime(&now);

  newyear.tm_hour = 0;
  newyear.tm_min = 0;
  newyear.tm_sec = 0;
  newyear.tm_mon = 0;
  newyear.tm_mday = 1;

   seconds = difftime(now, mktime(&newyear));
   printf ("%.f seconds since new year in the current timezone.\n", seconds);
   return 0;
 }
    
asked by anonymous 07.07.2018 / 22:02

1 answer

1

Missing code there for your program to behave the way you described!

Here is a tested and commented code that can solve your problem:

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

#define BUF_TAM_MAX (32)

int main( void )
{
    int ret = 0;
    char buf[BUF_TAM_MAX];
    struct tm tma, tmb;
    time_t diff;

    /* Inicializa struct tm */
    memset( &tma, 0, sizeof(tma) );
    memset( &tmb, 0, sizeof(tmb) );

    /* Le data inicial */
    printf("Entre com a data inicial (DD/MM/AAAA): ");
    fgets( buf, sizeof(buf), stdin );

    /* Desmonta data inicial */
    ret = sscanf( buf, "%02d/%02d/%04d", &tma.tm_mday, &tma.tm_mon, &tma.tm_year );

    if(ret != 3 )
    {
        printf("Data Inicial Invalida!\n");
        return 1;
    }

    /* Ajusta struct tm inicial */
    tma.tm_mon -= 1;
    tma.tm_year -= 1900;

    /* Le data final */
    printf("Entre com a data final (DD/MM/AAAA): ");
    fgets( buf, sizeof(buf), stdin );

    /* Desmonta data final */
    ret = sscanf( buf, "%02d/%02d/%04d", &tmb.tm_mday, &tmb.tm_mon, &tmb.tm_year );

    if(ret != 3 )
    {
        printf("Data Final Invalida!\n");
        return 1;
    }

    /* Ajusta struct tm final */
    tmb.tm_mon -= 1;
    tmb.tm_year -= 1900;

    /* Calcula diferenca em segundos */
    diff = difftime( mktime(&tmb), mktime(&tma) );

    /* Exibe resultados */
    printf( "Diferenca em segundos: %ld\n", diff );
    printf( "Diferenca em minutos: %ld\n", diff / 60 );
    printf( "Diferenca em horas: %ld\n", diff / (60 * 60) );
    printf( "Diferenca em dias: %ld\n", diff / (60 * 60 * 24) );

    return 0;
}

Testing:

Entre com a data inicial (DD/MM/AAAA): 12/09/1997
Entre com a data final (DD/MM/AAAA): 12/09/2018
Diferenca em segundos: 662688000
Diferenca em minutos: 11044800
Diferenca em horas: 184080
Diferenca em dias: 7670
    
08.07.2018 / 02:37