我正在用 c 语言编写一个程序,该程序需要具有必须有效且在当前日期之后的随机日期。对于这一代人来说,根本没有任何问题。我唯一不能做的就是只接受最新的日期。
我已经尝试首先检查日期是否有效,然后检查是否大于当前日期。然后我尝试做相反的事情,但这些解决方案都不起作用。
这是检查日期的函数:
short dateControl( const unsigned short day, const unsigned short month, const unsigned short year, const int min_year, const int max_year, struct tm curTime)
{
short correct = ZERO;
if( (year >= curTime.tm_year) && (year <= max_year) ){
if( (month >= 1) && (month <= 12) ){
if( (day >= 1 && day <= 31) && (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) ){
correct = ONE;
}else if( (day >= 1 && day <= 30) && (month == 4 || month == 6 || month == 9 || month == 11) ){
correct = ONE;
}else if( (day >= 1 && day <= 28) && (month == 2) ){
correct = ONE;
}else if( day == 29 && month == 2 && (year % 400 == 0 ||(year % 4 == 0 && year % 100 != 0)) ){
correct = ONE;
}else{
correct = ZERO;
}
} else{
correct = ZERO;
}
}else{
correct = ZERO;
}
if(correct == ONE){
if( year > curTime.tm_year ){
correct = ONE;
}else if( year == curTime.tm_year ){
if( month > curTime.tm_mon ){
correct = ONE;
}else if( month == curTime.tm_mon ){
if( day > curTime.tm_mday ){
correct = ONE;
}else if(day == curTime.tm_mday){
correct = ZERO;
}else if(day < curTime.tm_mday){
correct = ZERO;
}
}else if( month < curTime.tm_mon ){
correct = ZERO;
}
}
}
}
return correct;
}
这是生成日期的部分
day = random_int(1, 31);
month = random_int(1, 12);
year = random_int(local->tm_year, local->tm_year + 1);
validDate = dateControl(tempTrip.dep_date.day, tempTrip.dep_date.month, tempTrip.dep_date.year, local->tm_year, (local->tm_year + 1), *local);
while(validDate == ZERO){
tempDriver.sub_date.day = random_int(1, 31);
tempDriver.sub_date.month = random_int(1, 12);
tempDriver.sub_date.year = random_int(local->tm_year, (local->tm_year + 1));
validDate = dateControl(tempTrip.dep_date.day, tempTrip.dep_date.month, tempTrip.dep_date.year, local->tm_year, (local->tm_year + 1), *local);
}
}
我预计,如果生成的日期是 2/7/2019 而今天是 18/8/2019,则需要丢弃生成的日期并生成另一个日期。
最佳答案
i'm doing a program in c that needs to have random dates that have to be valid and after the current date. For the generation there aren't any problems at all. The only thing i can't do is to accept only the up to date dates.
您需要确定日期是否有效这一事实表明您生成随机日期的方式存在问题。
具体来说,如果您获取当前时间(使用 time()
)并向其添加一个随机正值(同时小心避免溢出),然后将结果转换为日期 (例如使用gmtime()
);那么您可以保证随机日期是有效的并且在将来,而无需进行任何检查,并且您可以删除所有 dateControl()
代码。
关于c - 验证截至当前时间的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57543954/