I'm trying to code ac function that calculates de number of DAYS between two dates ( format: yyyy-mm-dd ) using time.h.
The date is read from a string. I don't need to account for seconds or minutes.
I know I probably need to use difftime() but how can It be used in that format?
Thank you,
This is what I tried to do but I get segmentation fault.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define CURRDATE "2019-10-5"
#define OTHER "2019-10-10"
void auxDate(struct tm *t, char *date)
{
struct tm p;
p.tm_year = atoi(strtok(date, "-")) - 1900;
p.tm_mon = atoi(strtok(date, "-"));
p.tm_mday = atoi(date);
*t = p;
}
int main()
{
struct tm date1, date2;
auxDate(&date1, CURRDATE);
auxDate(&date2, OTHER);
printf("%.0lf\n", difftime(mktime(&date1), mktime(&date2)));
}
Code fails for various reasons.
"2019-10-5"
is a string literal that strtok(date, "-")
attempts to modify. This leads to undefined behavior (UB). Certainly the cause of the segmentation fault.
Instead use void auxDate(struct tm *t, const char *date)
and parse date
without attempting to change it. See strspn()
and strcspn()
.
mktime(&date1)
uses a not completely assigned struct tm
. Initialize all struct tm
members with struct tm p = { 0 };
. Otherwise the uninitialized members can provide erroneous values to mktime()
.
.tm_mon
is the number of month since January. I'd expect a - 1
somewhere.
Since difftime()
return the difference in seconds and the goal is difference in days. Division by the seconds-per-day is missing.
The are other corner case to solve that involve daylight savings time and redefinitions of a timezone's offset that will shift the time differences by a hour or so.
To handle, code could use the time at noon and set the DST to -1
p.tm_hour = 12;
p.tm_isdst = -1;
Then round the division:
days = round(difftime(...)/(24.0*60*60));
Even this will not handle very rare cases when a Pacific area timezone changed which side of the international date line it was on, which effectively repeated or cancelled a day.
On the good side, your posted code does compile.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.