Calculating date and time

0

I'm using the tm framework of header time.h as follows:

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

int main()
{
    struct tm dt_current, dt_begin;

    dt_current.tm_year = 2018;
    dt_current.tm_mon = 11;
    dt_current.tm_mday = 13;

    dt_current.tm_hour = 9;
    dt_current.tm_min = 45;
    dt_current.tm_sec = 0;

    printf("Data %d/%d/%d\n", dt_current.tm_mday, dt_current.tm_mon, dt_current.tm_year);
    printf("Hora %d:%d\n", dt_current.tm_hour, dt_current.tm_min);
    printf("-----------------\n");
    printf("10 dias atras\n");

    dt_begin = dt_current;
    dt_begin.tm_mday = dt_begin.tm_mday - 30;
    printf("Data %d/%d/%d\n", dt_begin.tm_mday, dt_begin.tm_mon, dt_begin.tm_year);
    printf("Hora %d:%d\n", dt_begin.tm_hour, dt_begin.tm_min);

    return 0;
}

Is there a function that I can remove in days from the date (dt_current) or do I need to do the treatment manually?

    
asked by anonymous 13.11.2018 / 13:29

1 answer

1

With the tm structure of lib time.h you can assign system date or one manually, the point is that once you do some operation with your date you need to validate it and this is done with the mktime command.

struct tm dt_current;

dt_current.tm_year = 2018;
dt_current.tm_mon = 11;
dt_current.tm_mday = 13;
dt_current.tm_hour = 9;
dt_current.tm_min = 45;
dt_current.tm_sec = 0;

dt_current.tm_mday = dt_current.tm_mday - 30; // Voltar 30 dias

printf("%d/%d/%d\n", dt_current.tm_mday, dt_current.tm_mon, dt_current.tm_year);
// Saida: 17/11/2018 -> ESTA ERRADO

mktime(&dt_current); //Recalcular a data
printf("%d/%d/%d\n", dt_current.tm_mday, dt_current.tm_mon, dt_current.tm_year);
// Saida: 14/10/2018

The same can be done with the hours.

    
13.11.2018 / 23:03