LocalDate
类是JDK
自带的java.time
包一个表示日期的时间类,用于进行日期的比较、运算等非常方便,这里介绍一些简单的使用方法
1、创建LocalDate类
1 2 3 4 5 6
| LocalDate today = LocalDate.now();
LocalDate localDate = LocalDate.of(2024, 1, 1);
LocalDate parseLocalDate = LocalDate.parse("2024-01-01");
|
2、Date和LocalDate的相互转化
Date
转化为LocalDate
1 2 3
| Date todayDate = new Date(); LocalDate todayLocalDate = todayDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
|
LocalDate
转化为Date
1 2 3
| LocalDate todayLocalDate = LocalDate.now(); Date todayDate = Date.from(todayLocalDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
|
注:LocalDate转化为Date后,对应的Date的时分秒都是0,因为LocalDate只有日期
3、日期比较
1 2 3 4 5 6 7 8
| LocalDate localDate1 = LocalDate.of(2024, 1, 1); LocalDate localDate2 = LocalDate.of(2024, 1, 2);
boolean before = localDate1.isBefore(localDate2);
boolean equal = localDate1.isEqual(localDate2);
boolean after = localDate1.isAfter(localDate2);
|
4、增加日期
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| LocalDate localDate = LocalDate.of(2024, 1, 1);
LocalDate plusDays = localDate.plusDays(1);
LocalDate plusWeeks = localDate.plusWeeks(1);
LocalDate plusMonths = localDate.plusMonths(1);
LocalDate plusYears = localDate.plusYears(1);
Period periodToAdd = Period.ofYears(2).plusMonths(3).plusDays(5); LocalDate plus = localDate.plus(periodToAdd);
LocalDate plus1 = localDate.plus(2, ChronoUnit.WEEKS);
|
减少日期只需要把数字改为负数即可
Period
、ChronoUnit
、Duration
,DayOfWeek
等都是java.time
包的,常用的类之一
5、获取指定条件的日期
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| LocalDate localDate = LocalDate.of(2024, 1, 1);
LocalDate firstDayOfYear = localDate.with(TemporalAdjusters.firstDayOfYear()); LocalDate lastDayOfYear = localDate.with(TemporalAdjusters.lastDayOfYear());
LocalDate firstDayOfMonth = localDate.with(TemporalAdjusters.firstDayOfMonth()); LocalDate lastDayOfMonth = localDate.with(TemporalAdjusters.lastDayOfMonth());
LocalDate firstMondayInMonth = localDate.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)); LocalDate lastMondayInMonth = localDate.with(TemporalAdjusters.lastInMonth(DayOfWeek.MONDAY));
LocalDate monday = localDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)); LocalDate sunday = localDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
|
6、获取日期的相关信息
1 2 3 4 5 6 7 8 9 10 11 12 13
| LocalDate localDate = LocalDate.of(2024, 2, 1);
int dayOfWeek = localDate.getDayOfWeek().getValue();
int dayOfMonth = localDate.getDayOfMonth();
int dayOfYear = localDate.getDayOfYear();
int monthValue = localDate.getMonthValue();
int i = localDate.get(WeekFields.of(DayOfWeek.MONDAY, 7).weekOfYear());
|