java.time包 时间处理类
已经习惯用 Date类这里就不再赘述,下面介绍新的时间处理类
1.LocalDate类
// 本地日期
LocalDate localDate = LocalDate.of(2022, 2, 27);
System.out.println(localDate);
int year = localDate.getYear(); //那一年
System.out.println("year = " + year);
Month month = localDate.getMonth(); // 第几个月
System.out.println("month = " + month);
int dayOfMonth = localDate.getDayOfMonth(); //一个月的第几天
System.out.println("dayOfMonth = " + dayOfMonth);
DayOfWeek dayOfWeek = localDate.getDayOfWeek(); //一周的第几天
System.out.println("dayOfWeek = " + dayOfWeek);
int lenth = localDate.lengthOfMonth(); // 一个月的天数
System.out.println("lenth = " + lenth);
boolean leapYear = localDate.isLeapYear(); // 是否是闰年
System.out.println("leapYear = " + leapYear);
//获取当前日期
System.out.println("LocalDate.now() = " + LocalDate.now());
2.LocalTime 类
// LocalTime 包含具体时间
LocalTime localTime = LocalTime.of(15, 10, 59);
System.out.println("localTime = " + localTime);
3.LocalDateTime 类(现在一般时间类型就是这个)
// LocalDateTime包括LocalDate和LocalTime
LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
System.out.println("localDateTime = " + localDateTime);
//LocalDateTime 和 LocalDate, LocalTime 相互转换
LocalDate localDate1 = localDateTime.toLocalDate();
LocalTime localTime1 = localDateTime.toLocalTime();
4.Instant类
// 一个时间戳
Instant instant = Instant.now();
System.out.println("instant = " + instant);
5.Duration类
// 一个时间段
Duration duration = Duration.between(localDateTime, localTime1);
long toDays = duration.toDays(); // 这个时间段中有几天
long toHours = duration.toHours(); // 这个时间段中有几个小时
// 通过of创建时间段
Duration duration1 = Duration.of(4, ChronoUnit.DAYS);
6.Period类
// 以年月日来表示时间段 Period period = Period.between(localDate, localDate1);
7.时间加减操作
// 时间加减操作
LocalDate date = LocalDate.now();
LocalDate localDate2 = date.minusDays(6);
LocalDate localDate3 = date.plusYears(11);
date.plus(4, ChronoUnit.DAYS);
System.out.println("localDate3 = " + localDate3);
System.out.println("localDate2 = " + localDate2);

浙公网安备 33010602011771号