Java Program to check the birthday and print Happy Birthday message

JavaObject Oriented ProgrammingProgramming

In this article, we will understand how to check the birthday and print Happy Birthday message. Checking the birthday is accomplished by comparing the present day and the given birthday.

Below is a demonstration of the same −

Input

Suppose our input is −

Birthday Date: 15 July

Output

The desired output would be −

Today’s Date is 20-12-2021
Today is not my birthday

Algorithm

Step 1 - START
Step 2 - Declare variables for month and dates values namely month_of_birth and
date_of_birth
Step 3 - Read the required values from the user/ define the values
Step 4 - Use LocalDate.now() function to get the current date and store it in the variable.
Step 5 – Using an if loop, compare the current month and date value with the input date and
month values respectively. If the values match, the result is true.
Step 5- Display the result
Step 6- Stop

Example 1

import java.time.LocalDate;
import java.time.Month;
public class HappyBirthday {
   public static void main(String args[]) {
      int date_of_birth = 15;
      Month month_of_birth = Month.JULY;
      System.out.println("The required packages have been imported");
      LocalDate current_date = LocalDate.now();
      System.out.println("Today's Date is " + current_date);
      System.out.println("The birthday is defined as : " +date_of_birth + " " +month_of_birth);
      int date = current_date.getDayOfMonth();
      Month month = current_date.getMonth();
      if(date == date_of_birth && month == month_of_birth) {
         System.out.println("HAPPY BIRTHDAY TO YOU !!");
      } else {
         System.out.println("Your birthday is not today ");
      }
   }
}

Output

The required packages have been imported
Today's Date is 2022-02-09
The birthday is defined as : 15 JULY
Your birthday is not today

Example 2

Here, the integer has been previously defined, and its value is accessed and displayed on the console.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Birthday {
   public static void main(String[] args) throws ParseException {
      SimpleDateFormat s = new SimpleDateFormat("MM-dd");
      Date today = s.parse("10-15");
      Date my_birthday_date = s.parse("10-15");
      System.out.println("The birthday date is defined as October 15th" );
      if (today.compareTo(my_birthday_date) == 0) {
         System.out.println("Happy Birthday!!");
      } else {
         System.out.println("Today is not tour birthday");
      }
   }
}

Output

The birthday date is defined as October 15th
Happy Birthday!!
raja
Updated on 21-Feb-2022 12:35:03

Advertisements