Instant、LocalTime、LocalDate、LocalDateTime介绍


Preface

Newly added time class in java1.8


1. Instant (represents a timestamp)

It can accurately drop nanoseconds. When using nanoseconds to represent a time, it is not enough to use a Long type. It needs a little more space. Its internal is composed of two Long fields. The first part represents the time from January 1, 1970. The current number of seconds, the second part represents the number of nanoseconds
Instant instant = Instant.now();//获取当前时间
System.out.println(instant);

1.1 Other methods of Instant

//计算5天前的时间
  Instant instant1 =  instant.minus(5, ChronoUnit.DAYS);
  System.out.println(instant1);

  //计算5天前的第二种方法
   Instant instant2 =  instant.minus(5, ChronoUnit.DAYS);
   System.out.println(instant2);

1.1.1 Comparison method

It provides two methods for comparing isAfter() and isBefore()

1.1.2 Get the number of seconds

//得到秒数
        Instant now = Instant.now();
        System.out.println(now.getEpochSecond());//秒
        System.out.println(now.toEpochMilli());//毫秒

1.2 Conversion

Because Instant is a timestamp, you can create a ZonedDateTime by adding a time zone, and then you can get the LocalDateTime of the corresponding time zone.
The following is the conversion diagram
Insert picture description here

Two, LocalTime (time without time zone)

1. Basic method

  //获取当前时间包含毫秒数---打印出->15:46:22.300
      LocalTime localTime = LocalTime.now();

     //构建时间---打印出->12:20:13
      LocalTime localTime1 = LocalTime.of(12,20,13);

      //获取当前时间不包含毫秒数---打印出来->15:49:37
      LocalTime localTime2 = localTime.withNano(0);

      //字符串可以转为时间---打印出来->12:15:12
      LocalTime localTime3 = LocalTime.parse("12:15:12");

    //判断localTime是否比localTime2晚
      System.out.println(localTime.isAfter(localTime2));
        
     //修改毫秒值
      System.out.println(localTime.withNano(22345));

Three, LocalDate (date without time zone)

## 3.1 Common methods
 LocalDate localDate = LocalDate.now();
        //获得2020年的第23天
        localDate = LocalDate.ofYearDay(2020,23);
        
        //2013年8月10日
        localDate = LocalDate.of(2013, Month.AUGUST,10);

Four, LocalDateTime

It is a combination of LocalDate and LocalTime, representing the date and time without time zone.

to sum up

For example: The above is what I will talk about today. This article only briefly introduces the use of Java time classes.

Guess you like

Origin blog.csdn.net/qq_44688861/article/details/113863093