Java 8 Date Time API
Java 8 further strengthens the handling of dates and times by releasing the new Date-Time API (JSR 310).
In the old version of Java, the date-time API had many problems, including:
Non-thread-safe− java.util.Date is not thread-safe, and all date classes are mutable. This is one of the biggest problems with Java date classes.
Poor design− The definitions of Java's date/time classes are not consistent. Date classes exist in both the java.util and java.sql packages. Additionally, classes for formatting and parsing are defined in the java.text package. java.util.Date contains both date and time, while java.sql.Date contains only date. Putting it in the java.sql package is unreasonable. Furthermore, these two classes have the same name, which is a very bad design in itself.
Troublesome time zone handling− The date classes do not provide internationalization and have no time zone support. Therefore, Java introduced the java.util.Calendar and java.util.TimeZone classes, but they also have all the above problems.
Java 8, in thejava.timepackage, provides many new APIs. The following are two of the more important APIs:
Local (local)− Simplifies date-time handling, without the issue of time zones.
Zoned (time zone)− Handles date-time with the specified time zone.
The new java.time package covers all operations for handling dates, times, date/time, time zones, instants, process (during), and clock.
Local Date-Time API
The LocalDate/LocalTime and LocalDateTime classes can be used in cases where time zone handling is not necessary. The code is as follows:
Java8Tester.java file
Executing the above script, the output is:
$ javac Java8Tester.java $ java Java8Tester 当前时间: 2016-04-15T16:55:48.668 date1: 2016-04-15 月: APRIL, 日: 15, 秒: 48 date2: 2012-04-10T16:55:48.668 date3: 2014-12-12 date4: 22:15 date5: 20:15:30
Zoned Date-Time API
If we need to take time zones into account, we can use the zoned date-time API:
Java8Tester.java file
Executing the above script, the output is:
$ javac Java8Tester.java $ java Java8Tester date1: 2015-12-03T10:15:30+08:00[Asia/Shanghai] ZoneId: Europe/Paris 当期时区: Asia/Shanghai
Other extensions
Java 8 New Features