Search code examples
cdatetimecodeblockscountdown

Calculating the time until christmas day in c


I'm trying to write a program in c that tells you how many days it is until Christmas. I've never worked with the time.h library before so I'm winging most of it. I can get the current time easy enough but my problem is that I'm not sure how to enter the information for Christmas day properly which messes up the difftime calculation. The code below is outputting a different number each time it's run but no matter what I try I can't get it working.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
time_t currentDate;
time (&currentDate);

struct tm * now;
now = localtime (&currentDate);

struct tm xmas;
xmas = *localtime(&currentDate);
xmas.tm_yday = 359;

double seconds = difftime(asctime(&xmas),asctime(&now));

double days=seconds/86400;

printf("%g days\n", days);


return 0;
}

Solution

  • You are on the right track, but difftime takes variables of type time_t as arguments. Therefore, the 'now' variable you used is not needed. The 'xmas' variable you have should be initialized in a slightly different way from how you initialized it. Then you can use mktime() on it to convert it to type time_t for use in difftime().

    Note you can run/modify the following code in your browser for free in this coding sandbox: https://www.next.tech/projects/4d440a51b6c4/share?ref=1290eccd.

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    int main()
    {
        double seconds, days;
        time_t currentDate;
        struct tm *xmas, today;
    
        time (&currentDate);
    
        today = *localtime(&currentDate);
    
        xmas = localtime(&currentDate);
        xmas->tm_mon = 11; // 0 == January, 11 == December
        xmas->tm_mday = 25;
        if (today.tm_mday > 25 && today.tm_mon == 11)
            xmas->tm_year = today.tm_year + 1;
    
        seconds = difftime(mktime(xmas),currentDate);
        days = seconds/86400;
    
        printf("%g days\n", days);
    
        return 0;
    }
    

    Reference - http://www.cplusplus.com/reference/ctime/difftime/