How to declare a date variable in C?

Asked

Viewed 13,398 times

14

I need to create an abstract type of data that represents a person, containing name, date of birth and CPF, and create a variable which is a pointer to this TAD (no core program).

To a certain extent I know, but I don’t know which is the right kind to put in place of the "?".

struct pessoa
{
    char nome;
    double cpf;
    ?   Data_Nasc;
}x,*ptr;
ptr = &x;
  • Getting your introduction to C Data Structures? Good luck. :)

  • I thought you wanted some kind of date, not to stick the date in the frame anyway. I think you really need to read the material I gave you. This is Ambi.

  • I go after the material I pass moustache what I have to do is not over yet, I have to do that struct and then pass it to a function , in function it must be filled and I must have another function that prints what was filled in in the first function. I will try to study, because I still do not know how to do these maneuvers with the functions and what to learn will increase in my code, if not run you seek to help with the community here

  • 2

    CPF as double == problems when CPF starts with zero ;)

  • i switched to char Cpf just like the bigown told me and now I understand why I can’t do in kind double thanks Renan in class I’ve seen my teacher using this type for Cpf I’ll talk to her about it

5 answers

12

You don’t do this. C is not a language that makes abstractions so easy. Of course nothing prevents you from creating a type to save and manipulate dates, as you did in your previous question. Although the name, probably not adequate structure and does not have auxiliary functions to manipulate the structure, this is basically what should be done: create a structure, which is a type composed of members, and use this within another structure when necessary.

Outside this may use some kind of library ready, but for learning purposes do not think appropriate.

A base without wanting to be complete, optimized to the maximum, would be:

typedef struct {
    int ano;
    short mes;
    short dia;
} Data
struct pessoa {
    char nome;
    double cpf;
    Data data_nasc;
} x,*ptr;

I put in the Github for future reference.

I didn’t quite understand why use double as CPF. The correct would be a char * or char[12], but at worst, if you haven’t learned to play with it yet, be a long. The name is also wrong, or it would have to be a pointer or a array. The way it is only allows 1 character in the name.

  • to create a function that fills these two structures, I must declare :

  • func1(ptr, date, date);

  • fun1(int *ptr, int data ){ };

  • I have already arranged the variable name for char name[20];

  • bigown arranged the post so that Voce understand.

  • There’s something I need to fix ?

  • You can’t change the question, you have to make new ones. I’ll reverse the edit.

Show 2 more comments

5


The solution pointed out by colleague @Maniero, from the point of view of data abstraction is valid, however, he reinvented the wheel, because the standard library already has all the abstractions of date and time and all the functions necessary to manipulate them.

Most suitable to replace the ? would be the kind time_t defined by the standard library time.h. This type represents the amount of seconds that has passed since the date of January 1, 1970 at 00:00:00 (UTC), is considered the zero milestone of the calendar system used by computers.

Although the Gregorian calendar facilitates chronological reasoning for humans, when logical comparisons are desired, or calculations with dates on computers, this kind of calendar ends hindering the work.

For example, for us, to know what happened first, if it was something in 10/04/1977 12:45:15 or something at 10/03/1976 13:09:12 is something almost but to solve this on a computer all 6 fields would have to be analysed independently, although performed almost instantaneously does not cease to be a job extra that the processor could avoid if it made use of another format date. Let’s imagine a database with thousands of records and the processor receiving a command to put everything in order chronological, if we can make the comparisons with a single operation by registration instead of 6 operations/record the final time also will tend to be 6 times smaller.

The following example illustrates the conversion of a value of the type time_t for a date and time humanly readable:

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


int main( int argc, char * argv[] )
{
    time_t agora;
    char datahora[100];

    /* Recupera a quantidade de segundos desde 01/01/1970 */
    agora = time(NULL);

    /* Formata a data e a hora da forma desejada */
    strftime( datahora, sizeof(datahora), "%d.%m.%Y - %H:%M:%S", localtime( &agora ) );

    printf( "Data/Hora: %s\n", datahora );

    return 0;
}

Already another, illustrates how to read a date and time in human format for the amount of seconds from ground zero:

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

char datahora[] = "01.01.2016 - 12:00:00";  

int main( int argc, char * argv[] )
{
    struct tm tm; 
    int ano, mes; 

    sscanf( datahora, "%d.%d.%d - %d:%d:%d", &tm.tm_mday, &mes, &ano, &tm.tm_hour, &tm.tm_min, &tm.tm_sec );

    tm.tm_year = ano - 1900;
    tm.tm_mon = mes - 1;

    printf( "Segundos desde 01/01/1970: %ld\n", mktime( &tm ) );

    return 0;
}

The best part is when we need to compare dates, we can use comparison operators, the same way we compare integers:

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

char datahora1[] = "12.01.2000 - 12:00:00"; 
char datahora2[] = "01.01.2015 - 13:10:20";  

int main( int argc, char * argv[] )
{
    time_t t1;
    time_t t2;

    struct tm tm; 
    int ano, mes; 

    sscanf( datahora1, "%d.%d.%d - %d:%d:%d", &tm.tm_mday, &mes, &ano, &tm.tm_hour, &tm.tm_min, &tm.tm_sec );

    tm.tm_year = ano - 1900;
    tm.tm_mon = mes - 1;

    t1 = mktime( &tm );

    sscanf( datahora2, "%d.%d.%d - %d:%d:%d", &tm.tm_mday, &mes, &ano, &tm.tm_hour, &tm.tm_min, &tm.tm_sec );

    tm.tm_year = ano - 1900;
    tm.tm_mon = mes - 1;

    t2 = mktime( &tm );

    if( t1 < t2 )
    {
        printf( "Data1 esta antes de Data2!\n");
    }
    else if( t1 > t2 )
    {
        printf( "Data1 esta depois Data2!\n");
    }
    else
    {
        printf( "Data1 eh iguaal a Data2!\n");
    }

    return 0;
}

I hope I’ve helped!

1

Note that it is not necessary for each data to be mapped to a variable in its structure. With this in mind, a simple solution is to have one variable for day, another for month plus one for year of birth.

struct pessoa
{
    char nome;
    double cpf;
    int dia_de_nascimento;
    int mes_de_nascimento;
    int ano_de_nascimento;
}

One remark: the field type nome of its structure is probably wrong, unless its program accepts only one-character names.

  • Pablo realized my mistakes when posting, in another post I will try to be more direct to the subject thanks

1

C has a type of data that stores dates. Uilque mentioned the library in his answer (time.h). It follows the official documentation in Portuguese:

http://pt.cppreference.com/w/c/chrono/tm

Here’s an example of how to get a current date on original in English:

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

int main(void)
{
    struct tm start = {.tm_mday=1};
    mktime(&start);
    printf("%s\n", asctime(&start));
}

If you’re doing this to learn on your own, I suggest starting with an easier language like C#, Java or Javascript (unless you already know them and want to really dive into C). Now, whether this is for a college or college assignment... your teacher is a madman or executioner. Continue to study to pass, but try to learn an easier language like the ones I mentioned. The date and time structures in these languages are much easier to use for those at the beginning.

  • because and Renan is a college assignment and only exercise 3 of 4

  • This is the exercise I have to do ... /*Create an abstract type of data that represents a person, containing name, date of birth and CPF. Create a variable which is a pointer to this TAD (in the main program ). Then create a function that receives this pointer and fill in the structure data and also a function that receives this pointer and prints the structure data. Finally, call this function in the main function. */ I am slowly trying to do what I have doubted I put here for the community to help me.

  • Hm... Unless the teacher objects, I would use a string to represent the date. Simpler and the problem is solved for now. When you really need to do operations with dates (see if the year is leap, pick the date from here to X days from today etc.) it is that you should worry about these more advanced structures. Trust me, preserve your sanity and pass the chair now, learn how to use dates professionally later.

  • truth and a good idea Dad, my teacher is more concerned if we can use the functions well, I can do what you said I will change my code and turn my date into a string

0

According to this example in Wikipedia, would be something like:

#include <time.h>

int main(void)
{
    time_t dataEHorario;

    // Você ainda pode setar a data para o atual do sistema
    current_time = time(NULL);

    exit(EXIT_SUCCESS);
}
  • Bigown learn a lot with Thanks, I always keep an eye on those links that pass me, solved me some doubts. Bigown If I want to use a function to fill this struct I must pass as parameter the right pointer ?

  • 1

    Uilque help a lot, certainly it was a doubt that in the future I would have.

  • 1

    @ALFAEX as you did not find mine a good solution, it is irrelevant, but could have a function to do this, could also do inline. When writing to the person using the @ before the name (he even help fill) and do in the person’s answer, so she is notified, I saw here by chance.

  • sorry I get lost still in the actions I take on the site, its solution is the most complete, only that I still do not know how to manipulate this data I will study what is typedef, I saw only a few topics about never deepened. I doubt how the code behaves .

  • @ALFAEX keeps asking us to help.

  • asking here in the comments or creating tags ?

Show 1 more comment

Browser other questions tagged

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