JDK1.8 series articles

  • New in JDK1.8 (1) : Lambda expressions
  • New in JDK1.8 (2) : Optional
  • JDK1.8 new feature (3) : Stream
  • New in JDK1.8 (4) : Maps
  • New JDK1.8 feature (5) : new date and time API

Java 8 includes a brand new date and time API in the java.time package. The new Date API is comparable to, but not identical to, the Joda-time library. The following examples cover the most important parts of the new API.

As mentioned in the “Alibaba Java Development Manual”, SimpleDateFormat is a thread unsafe class, generally do not define static variable, if defined as static, you must lock, or use the DateUtils tool class. Positive example: Be thread-safe and use DateUtils. The following treatment is also recommended:

private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {  
    @Override
    protected DateFormat initialValue(a) {
        return new SimpleDateFormat("yyyy-MM-dd"); }};Copy the code

Instant instead of Date, LocalDateTime instead of Calendar, DateTimeFormatter instead of Simpledateformatter, Simple beautiful strong immutable thread-safe

A Clock,

Clock provides access to the current date and time. Clocks are timezone dependent, and you can use System.currentTimemillis () to get the current number of microseconds. A particular point in time can also be represented using the Instant class, which can also be used to create older versions of java.util.Date objects.

Clock clock = Clock.systemDefaultZone();
long millis = clock.millis();

Instant instant = clock.instant();
Date legacyDate = Date.from(instant);   // legacy java.util.Date
Copy the code

Second, the Timezones

Time zones are represented by ZoneIDS and can be easily accessed through static factory methods. Time zones define offsets, which are important for transitioning between an instant and the local date and time.

System.out.println(ZoneId.getAvailableZoneIds());
// prints all available timezone ids

ZoneId zone1 = ZoneId.of("Europe/Berlin");
ZoneId zone2 = ZoneId.of("Brazil/East");
System.out.println(zone1.getRules());
System.out.println(zone2.getRules());

// ZoneRules[currentStandardOffset=+01:00]
// ZoneRules[currentStandardOffset=-03:00]
Copy the code

Third, a LocalTime

LocalTime indicates the time without a time zone, for example, 10pm or 17:30:15. The following example creates two local times for the time zone defined above. We then compare the two times and calculate the difference in hours and minutes between the two times.

LocalTime now1 = LocalTime.now(zone1); LocalTime now2 = LocalTime.now(zone2); System.out.println(now1.isBefore(now2)); // false long hoursBetween = ChronoUnit.HOURS.between(now1, now2); long minutesBetween = ChronoUnit.MINUTES.between(now1, now2); System.out.println(hoursBetween); // -3 System.out.println(minutesBetween); / / - 239Copy the code

LocalTime comes with various factory methods to simplify the creation of new instances, including parsing of time strings.

LocalTime late = LocalTime.of(23, 59, 59); System.out.println(late); // 23:59:59 DateTimeFormatter germanFormatter = DateTimeFormatter .ofLocalizedTime(FormatStyle.SHORT) .withLocale(Locale.GERMAN); LocalTime leetTime = LocalTime.parse("13:37", germanFormatter); System.out.println(leetTime); / / 13:37Copy the code

Four, LocalDate

LocalDate represents a different date, such as 2014-03-11. It is immutable and exactly like LocalTime. This example shows how to calculate a new date by adding or subtracting days, months, or years. Remember that each operation returns a new instance.

LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
LocalDate yesterday = tomorrow.minusDays(2);

LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
DayOfWeek dayOfWeek = independenceDay.getDayOfWeek();
System.out.println(dayOfWeek);    // FRIDAY
Copy the code

Parsing LocalDate from a string is as simple as parsing LocalTime:

DateTimeFormatter germanFormatter = DateTimeFormatter .ofLocalizedDate(FormatStyle.MEDIUM) .withLocale(Locale.GERMAN); LocalDate Xmas = localdate.parse ("24.12.2014", germanFormatter); System.out.println(xmas); / / 2014-12-24Copy the code

Fifth, LocalDateTime

LocalDateTime Indicates the date and time. As mentioned above, it combines the date and time into one instance. LocalDateTime is immutable and works like LocalTime and LocalDate. We can retrieve certain fields from date and time using methods:

LocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59); DayOfWeek dayOfWeek = sylvester.getDayOfWeek(); System.out.println(dayOfWeek); // WEDNESDAY Month month = sylvester.getMonth(); System.out.println(month); // DECEMBER long minuteOfDay = sylvester.getLong(ChronoField.MINUTE_OF_DAY); System.out.println(minuteOfDay); / / 1439Copy the code

Using the time zone information, you can convert it into a point-in-time Instant object. The Instant point-in-time object can be easily converted to a Date of type java.util.Date.

Instant instant = sylvester
        .atZone(ZoneId.systemDefault())
        .toInstant();

Date legacyDate = Date.from(instant);
System.out.println(legacyDate);     // Wed Dec 31 23:59:59 CET 2014
Copy the code

Formatting date time is just like formatting date or time. Instead of using predefined formats, you can create formatters using custom patterns.

DateTimeFormatter formatter =
    DateTimeFormatter
        .ofPattern("MMM dd, yyyy - HH:mm");

LocalDateTime parsed = LocalDateTime.parse("Nov 03, 2014 - 07:13", formatter);
String string = formatter.format(parsed);
System.out.println(string);     // Nov 03, 2014 - 07:13
Copy the code

Unlike java.text.NumberFormat, the new version of DateTimeFormatter is immutable and thread-safe.

The public,

If you want to see my updated Java direction learning article in the first time, you can follow the public account ** [Lucas’s Coffee shop]. All learning articles public number first, please scan the code to pay attention to oh! Java8 new features learning videos please pay attention to the public number, private message [Java8] ** can be free unscripted access to learning videos.