New Date Processing Tool for java8 Date/Time API

Keywords: Programming Java Excel Unix

Get on with the article New features of Java 8 Due to the large size of the previous article, the focus is not clear enough. This article takes out the Date/Time api of java8 to explain separately. The new date and time tools are all in java.time and its subpackages.

New Date/Time API Design Principles

The Java 8 Period/Time API is JSR-310 The goal of the specification implementation is to overcome all the shortcomings in the implementation of the old date/time API. Some design principles of the new date/time API are as follows:

  • Invariance: In the new date/time API, all classes are immutable, and this design is conducive to concurrent programming.
  • Separation of concerns: The new API clearly separates human-readable Date Time from machine Time stamp by defining different classes for Date, Time, Date Time, UNIX Time stamp and Time zone.
  • Clear: In all classes, methods are clearly defined to perform the same behavior. For example, to get the current instance, we can use the now() method, which defines format() and parse() methods in all classes, instead of having a separate class as before. In order to better handle the problem, all classes use factory mode and policy mode. Once you use the method of one class, it is not difficult to work with other classes.
  • Practical operations: All new date/time API classes implement a series of methods to accomplish common tasks, such as adding, subtracting, formatting, parsing, extracting individual parts from date/time, etc.
  • Scalability: The new date/time API works on the ISO-8601 calendar system, but we can also apply it to non-IOS calendars.

Common Classes and Their Use

Time can be roughly divided into three parts: date, time and time zone; among them, date is subdivided into year, month and day; time is subdivided into time, minute and second.

Normally machine time is expressed in seconds from 1970-01-01T00:00 to the present; here we correct a misconception that most people make, time stamp refers to seconds, not milliseconds.

Almost all time objects implement Temporal interfaces, so interface parameters are generally Temporal.

  • Instant: Represents a point on the timeline. The reference point is the standard Java epoch, i.e. 1970-01-01 T00:00:00Z (00:00 GMT, 1 January 1970).

  • LocalDate: Date value objects such as 2019-09-22

  • ** LocalTime:** Time value objects such as 21:25:36

  • ** LocalDateTime:** Date + Time Value Object

  • ** ZoneId:** Time zone

  • ** ZonedDateTime:** Date + Time + Time Zone Value Object

  • ** DateTime Formatter:** for date and time formatting

  • ** Period:** for calculating date intervals

  • ** Duration:** for calculating time intervals

Instant represents a point on the timeline (instantaneous)

// Test the time used to perform a new operation (nanosecond value)
Instant begin = Instant.now();
StreamMain streamMain = new StreamMain();
Instant end = Instant.now();
System.out.println(Duration.between(begin,end).toNanos());

LocalDate, LocalTime, LocalDateTime, ZonedDateTime can be grouped to represent time

// You can use the of method to build their instances, creating a time object for the East Eighth District of 2019-9-22 21:42:59 as follows 
LocalDate localDate = LocalDate.of(2019, Month.SEPTEMBER, 22);
LocalTime localTime = LocalTime.of(21, 42, 59);
LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.systemDefault());

// Getting the current time, this is a static method
LocalDate now = LocalDate.now();

// Each instance can obtain their part information, such as the year of acquisition. 
int year = localDate.getYear();

// You can modify the part information, which returns a new object, such as an additional year
LocalDate localDatePlus = localDate.plusYears(1);

// Setting up part information also returns new objects, such as set to 2017 
LocalDate localDateWithYear = localDate.withYear(2017);

// Compare two dates isAfter,isBefore
boolean after = localDate.isAfter(LocalDate.now());

// Format date and time
// yyyy-MM-dd
System.out.println(now.format(DateTimeFormatter.ISO_DATE));
// yyyy-MM-ddTHH:mm:ss
System.out.println(now.format(DateTimeFormatter.ISO_DATE_TIME));
// yyyy-MM-dd HH:mm:ss
System.out.println(now.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)));

// Date resolution 
System.out.println(LocalDate.parse("2019-09-22"));
System.out.println(LocalDateTime.parse("2019-09-22T21:05:22"));
System.out.println(LocalDateTime.parse("2019-09-22 21:05:22",DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)));

ZoneId is used to manipulate time zones. It provides a way to obtain all time zones and local time zones.

ZoneId zoneId = ZoneId.systemDefault();
Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();

Period, Duration can be considered as a set for calculating time intervals

// Create a two-week interval
Period periodWeeks = Period.ofWeeks(2);

// The interval of three months and two days in a year
Period custom = Period.of(1, 3, 2);

// The length of a day
Duration duration = Duration.ofDays(1);

// Calculate how long it has been since 2015/6/16 to 2019/09/22, which divides the interval into part s.
LocalDate now = LocalDate.now();
LocalDate customDate = LocalDate.of(2015, 6, 16);
Period between = Period.between(customDate, now);
// The result was 4:3:6, which was 4 years, 3 months and 6 days.
System.out.println(between.getYears()+":"+between.getMonths()+":"+between.getDays());

// Compare two instantaneous intervals 
Instant begin = Instant.now();
Instant end = Instant.now();
Duration.between(begin,end);

// You can also modify the part information and set the part information by returning a new object to represent the set value, while the original object remains unchanged.
Period plusDays = between.plusDays(1);
Period withDays = between.withDays(4);

Conversion with Date,Calendar

Although this new time tool is very useful, it is also useless if it is not compatible with the old api; fortunately, the new tool class can transform well with the previous tool class.

Intermediate conversion between Date, Calendar and Local DateTime, ZonedDateTime and Local Date by Instant

// Local DateTime to Date
Date localDateTimeDate = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
// Local DateTime to Calendar
Calendar localDateTimeCalendar = GregorianCalendar.from(ZonedDateTime.of(localDateTime, ZoneId.systemDefault()));

// Date to Local DateTime
LocalDateTime dateLocalDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
// Calendar to Local DateTime
LocalDateTime calendarLocalDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneOffset.systemDefault());

Relevant Source Location

https://gitee.com/sanri/example/tree/master/testjava8

A little promotion

Creation is not easy, I hope you can support my open source software, and my gadgets, welcome to gitee dot star, fork, bug.

Excel General Import and Export, Supporting Excel Formula Blog address: https://blog.csdn.net/sanri1993/article/details/100601578 gitee: https://gitee.com/sanri/sanri-excel-poi

Using template code to generate code from the database, as well as widgets that are often used in some projects Blog address: https://blog.csdn.net/sanri1993/article/details/98664034 gitee: https://gitee.com/sanri/sanri-tools-maven

Posted by cody44 on Tue, 24 Sep 2019 05:15:09 -0700