I have this function that gets the day before an input date:
Date dateDayBefore(char* inputDate)
{
struct tm dayBefore = { 0 };
char** fields = split(inputDate, 3, "/");
dayBefore.tm_mday = atoi(fields[0]);
dayBefore.tm_mon = atoi(fields[1]) - 1;
dayBefore.tm_year = atoi(fields[2]) - 1900;
dayBefore.tm_mday--;
mktime(&dayBefore);
char yesterday[10];
strftime(yesterday, sizeof(yesterday), "%d/%m/%Y", &dayBefore);
Date yesterdayDate = dateCreate(yesterday);
yesterdayDate.year += 1900;
return yesterdayDate;
}
Assume all other functions used are correct(such as split and dateCreate), they're used in other places where everything is as expected.
struct dayBefore
will contain the year but string yesterday
will not contemplate it after strftime
For: inputDate = 15/06/2020
expected result: 14/06/2020
actual result: 14/06/1900
Some screenshots of debugging:
You are trying to store a 10-character string (14/06/2020
) into a 10-character array, which leaves no space for the NULL.
Replace
char yesterday[10];
with
char yesterday[11];
There appears to be problems with how you are working with dates, but I can't address those right now.
Your question includes a lot of irrelevant details. You problem can be demonstrate using the following:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char* fields[] = { "15", "06", "2020" };
dayBefore.tm_mday = atoi(fields[0]);
dayBefore.tm_mon = atoi(fields[1]) - 1;
dayBefore.tm_year = atoi(fields[2]) - 1900;
dayBefore.tm_mday--;
mktime(&dayBefore);
char yesterday[10];
strftime(yesterday, sizeof(yesterday), "%d/%m/%Y", &dayBefore);
printf("%s\n", yesterday);
}