示例:检查生日并返回“生日快乐”消息
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
,则打印“生日快乐”消息。
另请阅读