java8 date api use

    java8 before date handling is not very convenient, the date you want to add or subtract, compare two date interval processing is very cumbersome, java8 to date to re-implement a set of api, located in java.time package.

    LocalDate display only the date

    LocalTime only display time

    LocalDateTime include both date and time

    Instant timestamp

    ZoneId time zone

1 Usage:

   LocalDate, LocalTime, LocalDateTime these class constructor is private, but they provide a static method to instantiate an object.

   1.1  of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)

          The method of specific values ​​can be passed, the particular configuration of the date and time:

     LocalDate localDate= LocalDate.of(2012,3,2);
LocalTime localTime = LocalTime.of(13, 1, 11);
LocalDateTime localDateTime = LocalDateTime.of(2012, 3, 2,13,1,11);
System.out.println(localDate);
System.out.println(localTime);
System.out.println(localDateTime);

             2012-03-02
             1:01:11 p.m.
             2012-03-02T13: 01: 11

    1.2 now()

           now method to get the current system time, the system defaults to the time zone, provides a method now (ZoneId) overloaded can specify the time zone passed

    1.3 parse()

          acceptable method may parse a time string, and a format mode

2 operation

    2.1 Providing each class plus (PLUS) minus (minus) operation method, the former can be easily calculated after day to day

    2.2 Each class has two dates provided Analyzing method isAfter, isBefore

    2.3 calculation interval two dates

    Duration between = Duration.between(localDateTime,localDateTime);

    2.4 Formatting Output

         format can accept a DateTimeFormatter, given a string formatted

   localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))

 

3 and Date interconversions

      Both are converted into corresponding time stamp, the time stamp to transformation by

    3.1 date 转LocalDate

  date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()

    3.2  LocalDate转date

   Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant())

   

   

 

Guess you like

Origin www.cnblogs.com/fencuo/p/12513233.html