Search code examples
cdatecomparisontime.h

Date comparison in C


I have some kind of task to make a C program that compares two dates and returns how many days are in between.

The thing is, identifier for variables should be one from time.h library, so I can't use strings or integers for those 2 dates. I know there is time_t identifier for variables in time.h but how do I go on to ask user input for variable with that type? I don't know % what should I put in printf or scanf for this type. Also, is there some way I could check if user input is valid?

And to compare those two, I guess I should be using difftime() function that is also contained in time.h, but then again, I am not sure. I read somewhere it shows difference in seconds, not sure if that source is legit, but I don't really need that. I need days, since I am working with dates.

There is not much material about this online, that is why I am asking for help. Thanks in advance!


Solution

  • I am assuming you only want number of days between two dates (not time). As mentioned in one of the comments, choose any format you want for the user input, and then parse it.

    One of the simplest formats to ask for as input for a date, is as an integer in the form of yyyymmdd.

    So for example if I wanted to find the number of days from my birthday this year (May 27, 2016) to Independence Day (July 4), I would enter into the program 20160527 and 20160704.

    As integers these are relatively easy to convert into month, day and year.

    Declare a struct tm and set the month day and year for each of these:

    // Lets say the above dates were read into integers indate1 and indate2,
    // so indate1 = 20160527 and indate2 = 20160704
    
    #include <time.h>
    
    struct tm dt = {0};
    dt.tm_year = (indate1/10000) - 1900;
    dt.tm_mon  = (indate1/100)%100;
    dt.tm_mday = (indate1%100);
    
    // Now convert to time_t:
    time_t dt1 = mktime(&dt);
    
    // Now do the same for indate2:
    dt.tm_year = (indate2/10000) - 1900;
    dt.tm_mon  = (indate2/100)%100;
    dt.tm_mday = (indate2%100);
    time_t dt2 = mktime(&dt);
    
    // Now take the difference between the two dates:
    double seconds = difftime( dt2, dt1 );
    
    // Now convert to number of days:
    unsigned long days = ( seconds / (60*60*24) );
    fprintf( stdout, "The number of days between those two dates is %ld\n", days);