Search code examples
cdatedateinterval

How to validate whether an input date is with in an date interval?


I'm using c language and our lesson now is about structures. Here's a portion of my code, and "temp" is a structure that also has a structure of date inside it. However, there are some cases that some valid dates can't go in until the last condition.

if( temp.Date.year >= start.year &&  temp.Date.year <= end.year)    
if( (temp.Date.year >= start.year &&  temp.Date.year <= end.year) && (temp.Date.month >= start.month &&  temp.Date.month <= end.month) )    
if( (temp.Date.year >= start.year &&  temp.Date.year <= end.year) && (temp.Date.month >= start.month &&  temp.Date.month <= end.month) && temp.Date.day >= start.day &&  temp.Date.day <= end.day)
                        isDateValid = 1;

Solution

  • Use KISS approach. Keep it small and simple.

    You could use a weird sequence of conditions or simply convert your date into something more handy.

    unsigned long start = start.Date.Year * 10000ul + start.Date.month * 100 + start.Date.day;
    

    Do the same for temp and end.

    This will give us some numerical values YYYYMMDD that can easily be compared.

    if (start <= temp && temp <= end)
        isValid = true;
    

    While this seems to be an excercise about structs, you might limit the use of the struct to extracting the values.