获取本地日期对象
LocalDate nowDate = LocalDate.now();
System.out.println("今天是:" + nowDate);
LocalDate bt = LocalDate.of(1997, 09, 16);
System.out.println(bt);//直接传入对应的年月日
System.out.println(LocalDate.of(1997, Month.SEPTEMBER, 16));//Month.NOVEMBER是枚举
获取年月日
int year = nowDate.getYear();
System.out.println("year:" + year);
int month = nowDate.getMonthValue();
System.out.println("month:" + month);int day = nowDate.getDayOfMonth();
System.out.println("day:" + day);//当年的第几天
int dayOfYear = nowDate.getDayOfYear();
System.out.println("dayOfYear:" + dayOfYear);//星期几
System.out.println(nowDate.getDayOfWeek());
System.out.println(nowDate.getDayOfWeek().getValue());//月份
System.out.println(nowDate.getMonth());
System.out.println(nowDate.getMonth().getValue());
比较日期对象
准备两个用于比较的日期对象
LocalDate myDate = LocalDate.of(2022, 12, 12);
LocalDate nowDate = LocalDate.now();System.out.println("今天是2022-09-16吗? " + nowDate.equals(myDate));//今天是2022-09-16吗? false
System.out.println(myDate + "是否在" + nowDate + "之前? " + myDate.isBefore(nowDate));//2018-09-05是否在2018-09-06之前? true
System.out.println(myDate + "是否在" + nowDate + "之后? " + myDate.isAfter(nowDate));//2018-09-05是否在2018-09-06之后? false
判断生日案例
准备生日的日期对象:
LocalDate birDate = LocalDate.of(1996, 8, 5);
准备今天的日期对象:
LocalDate nowDate = LocalDate.now();
获取月日对象
MonthDay birMd = MonthDay.of(birDate.getMonthValue(), birDate.getDayOfMonth());
MonthDay nowMd = MonthDay.from(nowDate);System.out.println("今天是你的生日吗? " + birMd.equals(nowMd));//今天是你的生日吗? false