Calculating Date and Time

Asked

Viewed 42 times

0

I’m using the tm header time. h structure 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;
}

Do you have a function that I can remove n days from date (dt_current) or need to do the treatment manually?

  • You have to do it manually. That’s all I wanted to know?

  • I thought of an easier way, turn datetime into days and subtract n days, then turn it back into datetime, it has some function that already does this or in the nail as well?

  • There is no type datetime all that be at hand.

1 answer

1

With the structure tm da lib time. h you can assign a system date or one manually, the point is that once you do some operation with your date it is necessary 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.