Why does Java8 need to introduce a new date and time library

  1. Date The Date output is not readable
    Date date = new Date();
    System.out.println(date);
    Copy the code

    The printout results:

    Sat Nov 14 11:03:41 CST 2020
    Copy the code
  2. Date parsing and formatting is difficult to implement using the JDK’s built-in API. A third-party Date and time library is usually used, for example:joda-time.commons-lang

What date and time classes are provided in Java8

There are a number of new classes available in the java.time package, and the main ones used areLocalDate.LocalTime.LocalDateTime.ZoneId.ZoneDateTime; The diagram is as follows:

  • The LocaDate class itself contains no time and time zone information, only date information; There are many ways to get common values: day of the week, month…

    The commonly used method of statically constructing LocaDate

    LocalDate.of(2020, 11, 14); Localdate. of(2020, month.November, 14); // Localdate. of(2020, month.November, 14); OfYearDay (2020, 10); // Use the Month enumeration class localdate.ofyearday (2020, 10); //2020年 10 月 10 日 => 2020-01-10 localdate.now (); System.out.println(localdate.now ()); // Better readability output => 2020-11-14Copy the code

    LocaDate common instance methods

    LocalDate now = LocalDate.of(2020, 11, 14); System.out.println(now.getMonth()); // Enumeration of months => NOVEMBER system.out.println (now.getMonthValue()); // Month number => 11 system.out.println (now.getDayofMonth ()); System.out.println(now.getDayofYear ())); // Day of a year => 319 system.out.println (now.getDayofweek ()); // Enumeration => SATURDAY system.out.println (now.lengthofmonth ()); System.out.println(now.lengthofyear ())); // How many days this year => 366Copy the code
  • LocalTime contains only time information

    LocalTime.of(12, 9, 10); // localtime.now (); LocalTime time = LocalTime.of(12, 9, 10); System.out.println(time.getHour()); System.out.println(time.getMinute()); System.out.println(time.getSecond());Copy the code
  • LocalDateTime can be seen from the name of this class is to merge the LocalDate LocalTime, only contains the date and time, do not include the time zone information structure, can be directly using a static method to create, but can be by LocalDate, LocalTime merge

    LocalDateTime.of(LocalDate.now(), LocalTime.now());
    LocalDateTime.of(2020, 11, 14, 13, 10, 50);
    LocalDate.now().atTime(LocalTime.now());
    LocalTime.now().atDate(LocalDate.now());
    LocalDateTime.now();
    Copy the code

    Because LocalDateTime is a combination of LocalDate and LocalTime, some instance methods of LocalDate and LocalTime can be found in LocalDateTime

  • Zoneids are used to replace timezones. Each ZoneId has a specific locale identifier.

      ZoneId.of("Asia/Shanghai");
      ZoneId.systemDefault()
    Copy the code

    To view all the region identifiers, enter the ZoneId source code

  • ZoneDateTime contains date, time, and time zone information. It is a combination of LocalDateTime and ZoneId

    ZonedDateTime zonedDateTime = ZonedDateTime.of(LocalDateTime.now(), ZoneId.systemDefault());
    ZonedDateTime.of(LocalDate.now(),LocalTime.now(),ZoneId.of("Asia/Shanghai"));
    Copy the code

Often we will encounter the need to require a time difference between the two times, how to achieve? Java8 also provides API support for Duration and Period

Duration between = Duration.between(LocalTime.of(13, 0), LocalTime.of(14, 0)); between.getSeconds(); // Return the number of seconds between the two time difference => 3600Copy the code

Duration specifies the length of time in seconds and milliseconds, so only two LocalTime, DateLocalTime, and ZonedDateTime can be handled. If LocalDate is passed in, an exception will be thrown

java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Seconds

	at java.time.LocalDate.until(LocalDate.java:1614)
	at java.time.Duration.between(Duration.java:475)
	at com.haixue.crm.stock.service.LocalTest.testDate(LocalTest.java:121)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Copy the code

Period can be used in this case

Period between1 = Period.between(LocalDate.of(2020, 11, 13), LocalDate.of(2020, 11, 13)); between1.getDays(); // Return the days of difference => 1Copy the code

More advanced manipulation of time and date

  • Changes to dates and times are added or removed through third-party dependencies, which are now supported by native apis
LocalDate now2 = LocalDate.of(2020, 11, 13); System.out.println(now2.plusDays(2)); // Add 2 days => 2020-11-15 system.out.println (now2.plusmonths (1)); System.out.println(now2.plusWeeks(1)); Println (now2.minusdays (1)); // Add a week => 2020-11-20 system.out.println (now2.minusdays (1)); Println (now2.minusmonths (1)); // Subtract 1 => 2020-11-12 system.out.println (now2.minusmonths (1)); System.out.println(now2.minusYears(1)); // Minus year => 2019-11-13 system.out.println (now2.withYear(2021)); // Minus year => 2019-11-13 system.out.println (now2.withYear(2021)); // Modify year => 2021-11-13Copy the code
  • Sometimes we have to take the last day of the month, the first day of the month, move the date to the next Sunday… ; These requirements can also be usedTemporalAdjusterGood implementation,TemporalAdjusterCan implement many custom date operations, Java8 inTemporalAdjustersMany implementations of the default have been provided.
LocalDate now3 = LocalDate.of(2020, 11, 13); System.out.println(now3.with(TemporalAdjusters.firstDayOfYear())); // first day of this year => 2020-01-01 system.out.println (now3. With (TemporalAdjusters. Next (dayofweek.monday))); / / the next Monday = > the 2020-11-16 System. Out. The println (now3. With (TemporalAdjusters. LastDayOfMonth ())); / / = > the 2020-11-30 System. The last day of this month the out the println (now3. With (TemporalAdjusters. LastDayOfYear ())); // Last day of the year => 2020-12-31Copy the code
  • The customTemporalAdjusterThe implementation gets the start time and end time of the day
LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 13, 10, 10, 10); System.out.println(localDateTime); System.out.println(localDateTime.with((temporal) -> temporal.with(ChronoField.SECOND_OF_DAY, 0))); System.out.println(localDateTime. With (temporal) -> temporal.with(ChronoField.SECOND_OF_DAY, temporal.range(ChronoField.SECOND_OF_DAY).getMaximum()))); // The last time of the day => 2020-11-13T23:59:59Copy the code

Parsing and formatting

Date string parsing and formatting operations are common. Let’s first look at how to implement date parsing without third-party packages

System.out.println(LocalDateTime.parse("2020-11-14T20:50:00")); / / output: 2020-11-14T20:50 System.out.println(LocalDateTime.parse("2020/11/14 20:50:00", DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"))); // Output: 2020-11-14T20:50Copy the code

Implementing formatting is also simple

LocalDate now4 = LocalDate.of(2020, 11, 13); System.out.println(now4.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"))); // Output: 2020/11/13 LocalDateTime localDateTime2 = localDatetime. of(2020, 11, 13, 10, 10, 10); System.out.println(localDateTime2.format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"))); // Output: 2020/11/13 10:10:10Copy the code

The last sentence

I am a newbie, if there is anything wrong, please point it out in the comments section