Reputation:
I have the following code:
int main(void) {
struct tm str_time;
time_t time_of_day;
str_time.tm_year = 2012-1900;
str_time.tm_mon = 6;
str_time.tm_mday = 5;
str_time.tm_hour = 10;
str_time.tm_min = 3;
str_time.tm_sec = 5;
str_time.tm_isdst = 0;
time_of_day = mktime(&str_time);
printf(ctime(&time_of_day));
return 0;
}
It works perfectly, but I can't find a way to verify that the date and time are in the code is the same as the computer, does anyone have any idea of how to compare both dates?
Upvotes: 1
Views: 379
Reputation: 153498
... have any idea of how to compare both dates?
OP is doing 3 things that contribute to potential time differences.
Code may not have filled all needed fields before calling mktime(&str_time);
. C specifies at least 9 fields. Best to zero-fill str_time
and then set the 7 fields. This is relatively a rare problem.
OP comments about date "2016-06-25 06:58:31". Yet does not post the values use to populate struct tm
. A common mis-code is that tm_mon
is the months since January, so a minus 1 is needed.
str_time.tm_year = 2016-1900;
str_time.tm_mon = 6 - 1;
str_time.tm_mday = 25;
str_time.tm_hour = 6;
str_time.tm_min = 58;
str_time.tm_sec = 31;
str_time.tm_isdst = tbd; // see below
str_time.tm_isdst = 0;
sets the timestamp to no daylight-savings-time. Often it is better to use str_time.tm_isdst = -1;
and let the system determine if DST was in effect.
Rather than compute the time_t
for a given user year-month-day, recommend to take the computer's time and convert that to year-month-day and then compare. Certainly any differences / discrepancies will be easier to understand.
To compare the computer local year-moth-day to user input
// February 20, 2016
int y = 2016;
int m = 2;
int d = 20;
time_t now;
if (time(&now) == -1) Handle_Error();
struct tm *tm = localtime(&now);
if (tm == NULL) Handle_Error();
if (((tm->tm_year + 1900) == y) && ((tm->tm_mon + 1) == m) && (tm->tm_mday == d)) {
puts("Dates match");
}
Upvotes: 2