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

1 Answer

0 votes
#include <iostream>
#include <ctime>

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

    // Convert to a tm structure (broken-down local time)
    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
    tm christmas = {};
    christmas.tm_year = year - 1900;  // Year since 1900
    christmas.tm_mon  = 11;           // December (0-based index)
    christmas.tm_mday = 25;           // 25th day of the month

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

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

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

    // Convert seconds → days (60 sec * 60 min * 24 hr)
    int days = static_cast<int>(seconds / (60 * 60 * 24));

    return days;
}

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

    std::cout << "Days until Christmas: " << days << std::endl;
}



/*
run:

Days until Christmas: 210

*/

 



answered 6 hours ago by avibootz
...