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

1 Answer

0 votes
//
// ---------------------------------------------------------
// Function: daysUntilChristmas
// Purpose : Calculate how many days remain until Christmas.
// ---------------------------------------------------------
//
function daysUntilChristmas() {
    // Get today's date from the system
    const today = new Date();

    // Extract the current year
    const year = today.getFullYear();

    // Build a date for Christmas of the current year
    let christmas = new Date(year, 11, 25); // December = month 11

    // If Christmas already passed this year, calculate for next year
    if (today > christmas) {
        christmas = new Date(year + 1, 11, 25);
    }

    // Calculate difference in milliseconds between today and Christmas
    const diffMs = christmas - today;

    // Convert milliseconds → days (1000 ms * 60 sec * 60 min * 24 hr)
    const days = Math.floor(diffMs / (1000 * 60 * 60 * 24));

    return days;
}

const days = daysUntilChristmas();

console.log("Days until Christmas:", days);



/*
run:

Days until Christmas: 210

*/

 



answered May 28 by avibootz
...