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

1 Answer

0 votes
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

//
// ---------------------------------------------------------
// Function: daysUntilChristmas
// Purpose : Calculate how many days remain until Christmas.
// ---------------------------------------------------------
//
public class Main {

    public static int daysUntilChristmas() {

        // Get today's date from the system
        LocalDate today = LocalDate.now();

        // Extract the current year
        int year = today.getYear();

        // Build a date for Christmas of the current year
        LocalDate christmas = LocalDate.of(year, 12, 25);

        // If Christmas already passed this year, calculate for next year
        if (today.isAfter(christmas)) {
            christmas = LocalDate.of(year + 1, 12, 25);
        }

        // Calculate difference in days between today and Christmas
        long days = ChronoUnit.DAYS.between(today, christmas);

        return (int) days;
    }

    public static void main(String[] args) {
        int days = daysUntilChristmas();

        System.out.println("Days until Christmas: " + days);
    }
}



/*
run:

Days until Christmas: 211

*/

 



answered 1 hour ago by avibootz
...