I'm studying C and thinking about a problem I came across the need to study the library time.h.
Basically, I would like to calculate the difference between two dates without needing to reinvent the wheel. For this I considered 2 hypothetical dates:
04/12/2018 12:00
04/12/2018 13:00
I hope the difference between these two dates is 1 hour (3600 seconds).
For this, I'm using the following routine:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void){
time_t seconds, sec1, sec2;
struct tm *dataTimeBegin = (struct tm *)malloc(sizeof(struct tm));
struct tm *dataTimeEnd = (struct tm *)malloc(sizeof(struct tm));
dataTimeBegin->tm_mday = 4;
dataTimeBegin->tm_mon = 11;
dataTimeBegin->tm_year = 2018 - 1900;
dataTimeBegin->tm_hour = 12;
dataTimeBegin->tm_min = 00;
dataTimeBegin->tm_sec = 00;
dataTimeEnd->tm_mday = 4;
dataTimeEnd->tm_mon = 11;
dataTimeEnd->tm_year = 2018 - 1900;
dataTimeEnd->tm_hour = 13;
dataTimeEnd->tm_min = 00;
dataTimeEnd->tm_sec = 00;
sec1 = mktime(dataTimeBegin);
sec2 = mktime(dataTimeEnd);
printf("sec1: %ld\n", sec1);
printf("sec2: %ld\n", sec2);
printf("difftime(sec2, sec1): %f", difftime(sec2, sec1));
return 0;
}
Contuno, I noticed strange behavior. My output indicates:
sec1: 1543935600
sec2: 1543935600
difftime (sec2, sec1): 0.000000
Why is sec2 the same as sec1? When I do:
dataTimeBegin->tm_mday = 4;
dataTimeBegin->tm_mon = 11;
dataTimeBegin->tm_year = 2018 - 1900;
dataTimeBegin->tm_hour = 13;
dataTimeBegin->tm_min = 00;
dataTimeBegin->tm_sec = 00;
dataTimeEnd->tm_mday = 4;
dataTimeEnd->tm_mon = 11;
dataTimeEnd->tm_year = 2018 - 1900;
dataTimeEnd->tm_hour = 13;
dataTimeEnd->tm_min = 00;
dataTimeEnd->tm_sec = 00;
My output is:
sec1: 1543939200
sec2: 1543935600
difftime (sec2, sec1): -3600.000000
This behavior does not make sense to me. Am I faltering in any concept?
EDIT: I have a problem with the struct, but I do not know how to do it. I have a pointer to struct, and I want to use the pointer.
EDIT 2: I followed the recommendation of zentrunix and initialized tm_isdst and it worked fine in both versions (with the use of the pointer or without)