Java学习_20220623

Java8 新特性

1.时间和日期

Instant类,时间戳/时间线,内部保存了从1970年1月1日00:00:00以来的秒和纳秒。 

Instant now = Instant.now();
System.out.println("now = " + now);
System.out.println("now.getNano() = " + now.getNano());//获取纳秒
System.out.println("now.getEpochSecond() = " + now.getEpochSecond());//获取秒

计算时间日期时间差

Duration:计算两个时间差(LocalTime)

LocalTime time = LocalTime.now();
LocalTime of = LocalTime.of(22, 42, 31);
//计算时间差
Duration duration = Duration.between(time,of);
System.out.println("相隔天数 = " + duration.toDays());//相隔天数 = 0
System.out.println("相隔小时数 = " + duration.toHours());//相隔小时数 = 13
System.out.println("相隔分钟数 = " + duration.toSeconds());//相隔分钟数 = 46865

Period:计算两个日期差(LocalDate)

LocalDate localDate = LocalDate.now();
LocalDate date = LocalDate.of(2016, 12, 31);
//计算日期差
Period period = Period.between(date, localDate);
System.out.println("相隔年 = " + period.getYears());//相隔年 = 5
System.out.println("相隔月 = " + period.getMonths());//相隔月 = 5
System.out.println("相隔日 = " + period.getDays());//相隔日 = 23

 时间校正器

 TemporalAdjuster:时间校正器

LocalDateTime localDateTime = LocalDateTime.now();
TemporalAdjuster adjuster = (temporal)->{
  LocalDateTime dateTime = (LocalDateTime) temporal;
  LocalDateTime nextMonth = dateTime.plusMonths(1).withDayOfMonth(1);
  return  nextMonth;
};
LocalDateTime nextMouth = localDateTime.with(adjuster);
System.out.println("nextMouth = " + nextMouth);//nextMouth = 2022-07-01T10:11:38.190750

 TemporalAdjusters:通过该类静态方法提高了大量常用的操作

LocalDateTime localDateTime = LocalDateTime.now();
LocalDate with = localDate.with(TemporalAdjusters.firstDayOfMonth());//这个月的第一天
System.out.println(with);//2022-06-01

 日期时间的时区

//获取所有时区id
ZoneId.getAvailableZoneIds().forEach(System.out::println);
//使用计算机默认的时区,创建日期时间
ZonedDateTime now1 = ZonedDateTime.now();
System.out.println("now1 = " + now1);//now1 = 2022-06-23T10:20:14.073556800+08:00[Asia/Shanghai]
//指定时区的日期
ZonedDateTime now2 = ZonedDateTime.now(ZoneId.of("America/Toronto"));
System.out.println("now2 = " + now2);

重复注解使用@Repeatable注解定义重复注释。

2 Optional类

解决空指针的问题 

//获取Optional中的值
//get():如果Optional中有值则返回,否则抛出NoSuchElementException异常
//get()通常和isPresent()方法一块使用
//isPresent():判断是否包含值,包含值返回true,不含值返回false
String s1 = op1.get();
System.out.println("s1 = " + s1);
if(op3.isPresent()){
    System.out.println(op2.get());
}else{
    System.out.println("无值");
}
posted @ 2022-06-23 16:19  浑浑噩噩一只小迷七  阅读(27)  评论(0)    收藏  举报