Search code examples
c++cdatecomparison

How to compare day/month/year in C or C++?


I have a program that asks the user to input to dates then it displays which one is more recent I've done it like this

if (year1>year2 || month1>month2 || day1>day2)
    return -1;

if (year1<year2 || month1<month2 || day1<day2)
    return +1;

but the output is not quite correct.


Solution

  • You need a much more complicated check than that:

    if (year1 > year2)
        return -1;
    else if (year1 < year2)
        return +1;
    
    if (month1 > month2)
        return -1;
    else if (month1 < month2)
        return +1;
    
    if (day1 > day2)
        return -1;
    else if (day1 < day2)
        return +1;
    
    return 0;
    

    NOTE: Returning -1 for first is greater than second seems counter-intuititive to me, however I have followed the semantics provided by the OP.