I have to calculate a date between a given date and now. I have tried the following piece of code which works mostly. However, it can give a date which is days or months ahead of the current date. First it calculates the amount of years between now and the given input date.
The problem is that if that if for example the given date is 1 March 1990
, the difference in years will be 25
. But that means the random date can also be 1 March 2015 (1990 + 25)
, which is in the future (as seen from today). Adding 24
years will make the latest possible date 31 December 2014
, which is not close enough to today.
So somewhere I am stuck calculating the right amount of years. Does anyone know how to solve this properly?
PS tell me if more code is needed, but all input is done correctly and the right libraries have been included.
void random_func(struct tm *input_date, struct tm *random_date) {
struct tm now;
time_t date_now= time(NULL);
now = *localtime(&date_now);
int years_in_between;
years_in_between = difftime(now.tm_year + 1900, input_date->tm_year);
srand(time(0));
random_date->tm_mday = (rand() % 31) + 1;
random_date->tm_mon = (rand() % 12) + 1;
random_date->tm_year = input_date->tm_year + rand() % years_in_between;
tm_set_zero(random_date);
}
void tm_set_zero(struct tm *tmStruct) {
tmStruct->tm_sec = 0;
tmStruct->tm_min = 0;
tmStruct->tm_hour = 0;
tmStruct->tm_wday = 0;
tmStruct->tm_yday = 0;
tmStruct->tm_isdst = 0;
}
Aucun commentaire:
Enregistrer un commentaire