How to work with C Dates?

Asked

Viewed 3,508 times

0

Speak up your people! I took a question here on the internet to do that nothing comes out at all. He asks the following: Want to make a program that reads the name of the book that will be borrowed, the type of user (teacher or student) and the date of book loan. The program should consider that the teacher has ten days to return the book and the student only five days. Should any of them return with delay, the program should calculate the fine related to this delay considering the amount of R $ 0,50 per delay day. The program should read the actual return date and at the end of the execution, it should print a receipt as shown below:

Name of the book: XXXXX

User type: XXXXX

Date of loan: XX/XX/XXXX

Expected date of return: XX/XX/XXXX

Date of return: XX/XX/XXXX

Late fine: R$ XXX,XX

-Name of the book: -Type of the user: -Date of the loan: -Expected date of return: -Date of return: -Late payment of a fine:

My biggest problem is with the dates, because I can’t operate with them.

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

int main(){
    setlocale(LC_ALL, "portuguese");
    char usuario[10], livro[30];
    int dia, mes, ano;

        printf("Insira o nome do livro: ");
        scanf("%s", &livro);
        printf("Insira o tipo do usuário: ");
        scanf("%s", &usuario);
        printf("Insira a data do emprestimo: ");
        scanf("%d%*c%d*c%d", &dia, &mes, &ano);



            if((usuario[0]=='A')&&(usuario[1]=='L')&&(usuario[2]=='U'))
            {
            Nessa função "if" eu iria colocar um for para contar os dias de 
            atraso entre data de emprestimo e data da devolução, por exemplo:          

            dataemp=dataemp+5 //Pois alunos tem 5 dias para devolver    
            for(i = 0; dataemp<=datadev; i++)
            multa = i * 0.50;


            }
            if((usuario[0]=='P')&&(usuario[0]=='R')&&(usuario[0]=='O'))
            {

            dataemp=dataemp+10 //Pois professor tem 10 dias para devolver    
            for(i = 0; dataemp<=datadev; i++)
            multa = i * 0.50;

            }


}

How can I take the user’s date, subtract these dates, and add days in the user’s date? I’ve read about time. h but I did not understand her well enough to implement my code with her. Ta fuck, seriously, 4 days trying to do this and do not pass the algorithm I wrote above.

  • In fact, on the lines of the form dataemp=dataemp+xxx, you forgot the semicolon at the end; inside the first if has a comment without the markers // or /* */; and you usually want to compare strings using strcmp() or strncmp(), thus: if (!strncmp(usuario, "ALU", 3))

1 answer

1

In C, there are no dates per se. The type that dates in C is actually a int that counts the number of seconds elapsed since 1 January 1970 UTC and the date in question. But to syntactically analyze a date like DD/MM/YYYY, you have to use another type and another function of the <time.h>, which is the mktime().

To mktime() receives a type structure struct tm and returns the time_t correspondent:

time_t
ler_data(const char data[11]) {
    struct tm tm = { 0 }; /* zera a struct toda */

    if (sscanf(data, "%d/%d/%d", &tm.tm_mday, &tm.tm_mon, &tm.tm_year) < 3) {
        fprintf(stderr, "Erro de formatação ao ler data %s\n", data);
        exit(1);
    }
    tm.tm_mon --; /* tm.mon espera o número de meses desde janeiro (0–11) */
    tm.tm_year -= 1900; /* tm.year espera o número de anos desde 1900 */

    return mktime(&tm);
}

Having this, the difference between dates A and B in days is (B - A) / 86400, since there are 24 60 60 = 86,400 seconds in a day. In fact it is better to do #define SEGUNDOS_EM_UM_DIA 86400 and then say (B - A) / SEGUNDOS_EM_UM_DIA. Also, to add up n days to a date A you do A + n * SEGUNDOS_EM_UM_DIA.

To do the reverse way, you will have to write the date in a buffer using localtime() to convert time_t in struct tm and then strftime() or snprintf() to convert the struct tm string:

void
escrever_data(char * buf, size_t len, time_t data) {
    struct tm * tm = localtime(&data);
    buf[0] = '\0';
    if (snprintf(buf, len, "%02d/%02d/%04d",
                           tm->tm_mday,
                           tm->tm_mon + 1,
                           tm->tm_year + 1900) < 10) {
        fprintf(stderr, "Erro de formatação ao escrever data 0x%08X\n", data);
        exit(1);
    }
}
  • Thanks @Wtrmute gave me a horizon, I will try to do the activity here!

Browser other questions tagged

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