简介
Java 8 中,有一部分代替了以往比较难用的 java.util.Date 类,并且创建了一套新的时间类型,该类型为:LocalDateTime
,并且提供了许多方法供我们使用,其中,LocalDate
、LocalTime
、LocalDateTime
是新API里的基础对象,绝大多数操作都是围绕这几个对象来进行的。
LocalDate
: 只含年月日的日期对象,对于LocalDate,只有精度大于或等于日的加减,如年、月、日;LocalTime
:只含时分秒的时间对象,对于LocalTime,只有精度小于或等于时的加减,如时、分、秒、纳秒;LocalDateTime
: 同时含有年月日时分秒的日期对象,对于LocalDateTime,则可以进行任意精度的时间相加减;
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
LocalDateTime yearStart = now.with(TemporalAdjusters.firstDayOfYear()).with(LocalTime.MIN);
LocalDateTime yearEnd = now.with(TemporalAdjusters.lastDayOfYear()).with(LocalTime.MAX);
System.out.println("当前年的开始时间:" + yearStart.format(fmt));
System.out.println("当前年的结束时间:" + yearEnd.format(fmt));
LocalDateTime monthStart = now.with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN);
LocalDateTime monthEnd = now.with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MAX);
System.out.println("当前月的开始时间:" + monthStart.format(fmt));
System.out.println("当前月的结束时间:" + monthEnd.format(fmt));
int dayOfWeek = now.getDayOfWeek().getValue();
LocalDateTime weekStart = now.minusDays(dayOfWeek - 1).with(LocalTime.MIN);
LocalDateTime weekEnd = now.plusDays(7 - dayOfWeek).with(LocalTime.MAX);
System.out.println("当前周的开始时间:" + weekStart.format(fmt));
System.out.println("当前周的结束时间:" + weekEnd.format(fmt));
LocalDateTime dayStart = now.with(LocalTime.MIN);
LocalDateTime dayEnd = now.with(LocalTime.MAX);
System.out.println("当天的开始时间:" + dayStart.format(fmt));
System.out.println("当天的结束时间:" + dayEnd.format(fmt));
}
//当前年的开始时间:2022年01月01日 00:00:00
//当前年的结束时间:2022年12月31日 23:59:59
//当前月的开始时间:2022年06月01日 00:00:00
//当前月的结束时间:2022年06月30日 23:59:59
//当前周的开始时间:2022年06月23日 00:00:00
//当前周的结束时间:2022年07月03日 23:59:59
//当天的开始时间:2022年06月28日 00:00:00
//当天的结束时间:2022年06月28日 23:59:59