How to calculate the number of days until Christmas from today in C

1 Answer

0 votes
#include <stdio.h>
#include <time.h>

//
// ---------------------------------------------------------
// Function: daysUntilChristmas
// Purpose : Calculate how many days remain until Christmas.
// ---------------------------------------------------------
//
int daysUntilChristmas() {
    // Get the current system time (seconds since 1970)
    time_t now = time(NULL);

    // Convert to a tm structure (local date/time)
    struct tm today = *localtime(&now);

    // Extract the current year (tm_year counts from 1900)
    int year = today.tm_year + 1900;

    // Build a tm structure for Christmas of the current year
    struct tm christmas = {0};
    christmas.tm_year = year - 1900;  // Year since 1900
    christmas.tm_mon  = 11;           // December (0-based index)
    christmas.tm_mday = 25;           // 25th day

    // Convert Christmas date to time_t
    time_t christmas_time = mktime(&christmas);

    // If Christmas already passed this year, use next year
    if (difftime(christmas_time, now) < 0) {
        christmas.tm_year += 1;       // Move to next year
        christmas_time = mktime(&christmas);
    }

    // Calculate difference in seconds
    double seconds = difftime(christmas_time, now);

    // Convert seconds → days
    int days = (int)(seconds / (60 * 60 * 24));

    return days;
}

int main() {
    int days = daysUntilChristmas();

    printf("Days until Christmas: %d\n", days);

    return 0;
}



/*
run:

Days until Christmas: 210

*/

 



answered 6 hours ago by avibootz
...