Save local time in a variable

1

I am trying to save the time of registration in a variable, for example, if the system registers a program execution at 3am I need to save it in a variable, but if I print the value of that variable at any other time, I always show me 3am

int *tiempo;
time_t currentTime = time(NULL);
time(&currentTime);
struct tm *myTime = localtime(&currentTime);
tiempo = myTime->tm_sec;
printf("Tiempo en segundos actual: %d\n", myTime->tm_sec);
printf("Tiempo registrado: %d\n", tiempo);

.

    
asked by Arath Jimenez 29.11.2017 в 01:19
source

1 answer

1
tiempo = myTime->tm_sec;

With that line you are only storing the seconds. If your idea is to store the full time, you also need to save the time and minutes:

tiempo = myTime->tm_hour * 3600 + myTime->tm_min * 60 + myTime->tm_sec;

Now, since in tiempo you are storing the encoded date in seconds it does not make much sense to print the value in the raw:

printf("Tiempo registrado: %d\n", tiempo);

Since you are going to return a value expressed only in seconds. Instead you would have to treat the variable before printing it:

int segundos = tiempo % 60;
tiempo /= 60;
int minutos = tiempo % 60;
int horas = tiempo / 60;

printf("Tiempo registrado: %02d:%02d:%02d\n", horas, minutos, segundos);

To simplify the task, it would be advisable to work with a variable of type time_t or struct tm . The reason is that there are functions that allow you to print and treat hours easily. For example, to print the full time you can do the following:

struct tm tiempo = localtime(time(NULL));
char buffer[50];
strftime (buffer,50,"%H:%M:%S",tiempo);

printf("Tiempo registrado: %d\n", buffer);

Or even, if your idea is to come out of am or pm you can do this:

struct tm tiempo = localtime(time(NULL));
char buffer[50];
strftime (buffer,50,"%I:%M:%S %p",tiempo);

printf("Tiempo registrado: %d\n", buffer);

Thus the time will be printed in 12 hours format and indicating if it is in the morning or in the afternoon ... and all without touching the code.

    
answered by 29.11.2017 / 07:45
source