Java Program to Check Birthday and Print Happy Birthday Message

In this Java program, we will check birthday and print happy birthday message on screen. This is a simple program that can be used to check if today is someone's birthday and print a message if it is.


Java Program to Check Birthday and Print Happy Birthday Message

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;

public class BirthdayChecker {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Please enter your birthdate (dd-MM-yyyy):");
        String birthdate = scanner.nextLine();

        // convert the birthdate string to a LocalDate object
        DateTimeFormatter formatter = DateTimeFormatter
            .ofPattern("dd-MM-yyyy");
        LocalDate bday = LocalDate.parse(birthdate, formatter);

        // get today's date
        LocalDate today = LocalDate.now();

        // compare the two dates
        if (bday.getMonthValue() == today.getMonthValue() && 
                bday.getDayOfMonth() == today.getDayOfMonth()) {
            System.out.println("Happy Birthday!");
        } else {
            System.out.println("Today is not your birthday.");
        }
    }
}
Output
Please enter your birthdate (dd-MM-yyyy):
20-03-1994
Today is not your birthday.

The program starts by prompting the user to enter their birthdate in the format "dd-MM-yyyy". The input is read using a Scanner object and stored in a variable called "birthdate".

Next, the program uses the LocalDate class and a DateTimeFormatter to convert the birthdate string to a LocalDate object. This object represents the user's birthdate.

The program then gets today's date using the LocalDate.now() method and stores it in a variable called "today". Finally, the program compares the month and day of the month of the two dates. If they match, it means today is the user's birthday, and the program prints "Happy Birthday!". If they do not match, it means today is not the user's birthday, and the program prints "Today is not your birthday."