📜  Java程序检查生日并打印生日快乐消息

📅  最后修改于: 2020-09-26 17:55:59             🧑  作者: Mango

在此示例中,我们将学习用生日检查当前日期,并使用Java打印“生日快乐”消息。

示例:检查生日并返回生日快乐消息
import java.time.LocalDate;
import java.time.Month;

public class Main {
   public static void main(String args[]) {

    // declare variables for birthday
    int birthDate = 23;
    Month birthMonth = Month.SEPTEMBER;

    // get current date
    LocalDate currentDate = LocalDate.now();
    System.out.println("Todays Date: " + currentDate);

    // get current date and month
    int date = currentDate.getDayOfMonth();
    Month month = currentDate.getMonth();

    if(date == birthDate && month == birthMonth) {
      System.out.println("HAPPY BIRTHDAY TO YOU !!");
    }
    else {
      System.out.println("Today is not my birthday.");
    }
   }
}

输出1

Todays Date: 2020-07-28
HAPPY BIRTHDAY TO YOU !!

在上面的示例中,

  • LocalDate.now() -返回当前日期
  • getDayOfMonth() -返回当前日期
  • getMonth() -返回当前月份

在这里,我们使用了if … else语句来检查当前日期是否匹配生日。如果为true ,则打印生日快乐消息。