Get the current date directly from the machine

Asked

Viewed 6,288 times

5

I need to implement in my project (library system) the functionality of getting the date directly from the machine. I wanted in the format dia/mês/ano, to generate the fine for late delivery of book automatically, however, I can only get this way:

Resultado

It is possible to get the date directly from the machine in the format I mentioned?

Follows the code:

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


int main(void)
{
    time_t mytime;
    mytime = time(NULL);
    printf(ctime(&mytime));

    return 0;
}

https://ideone.com/Sn0DSe

2 answers

4


You have to use the function localtime() to provide you with the date in a structure, then you can assemble as you like. There are people who create functions ready to abstract that.

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

int main(void) {
    time_t mytime;
    mytime = time(NULL);
    struct tm tm = *localtime(&mytime);
    printf("Data: %d/%d/%d/\n", tm.tm_mday, tm.tm_mon + 1, tm.tm_year + 1900);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

3

In the header file time.h there are functions and types of data to manipulate time and date information.

The type of data struct tm defines a structure to be used in functions working with date and time.

struct tm {
    int tm_sec;   // Indica os segundos de 0 a 59
    int tm_min;   // Indica os minutos de 0 a 59
    int tm_hour;  // Indica as horas de 0 a 24
    int tm_mday:  // Indica os dias do mês de 1 a 31
    int tm_mon;   // Indica os meses do ano de 0 a 11
    int tm_year;  // Indica o ano a partir de 1900
    int tm_wday;  // Indica o dia da semana de 0 (domingo) até 6 (sábado)
    int tm_yday;  // Indica o dia do ano de 1 a 365
    int tm_isdst; // Indica o horário de verão se for diferente de zero
};

The type of data time_t is used to represent calendar time.

The function localtime() receives the time in seconds of a variable of type time_t, converts to local time, stores the data in its structure and returns a pointer to a struct of the kind tm with the local data.

Example of use:

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

int main(void)
{
    struct tm *p;
    time_t seconds;

    time(&seconds);
    p = localtime(&seconds);

    printf("Dia do ano: %d\n", p->tm_yday);
    printf("Data: %d/%d/%d\n", p->tm_mday, p->tm_mon + 1, p->tm_year + 1900);
    printf("Hora: %d:%d:%d\n", p->tm_hour, p->tm_min, p->tm_sec);

    printf("\nGeral: %s\n", ctime(&seconds));

    return 0;
}

Browser other questions tagged

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