English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在此示例中,我们将学习用生日检查当前日期,并使用Java打印“生日快乐”消息。
import java.time.LocalDate; import java.time.Month; public class Main { public static void main(String args[]) { //声明生日变量 int birthDate = 23; Month birthMonth = Month.SEPTEMBER; //获取当前日期 LocalDate currentDate = LocalDate.now(); System.out.println("Today's date: ") + currentDate); //Get the 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."); } } }
Output1
Today's date: 2020-08-28 Happy birthday to you!!
In the above example,
LocalDate.now() - Return the current date
getDayOfMonth() - Return the current date
getMonth() - Return the current month
Here, we useif ... elseThe statement to check if the current date matches the birthday. If true, then printHappy BirthdayMessage.