LOCALDATE, 和 localdateti to localtime

The following are all my copy from https://mp.weixin.qq.com/s/FNsyV4skO4NauynR2igp5A

This copy is for the convenience of their own to find later - not involved in commercial use, the feeling of writing a more comprehensive and structured, so directly took to do a backup, I hope you will support the original author, see the original link

1 Overview

Java 8 to Date and Time introduces a new API, in order to address the shortcomings of the old java.util.Date and java.util.Calendar.

As part of this article, let's start with some of the problems existing Date and Calendar API, to explore new Java 8 Date and Time API how to solve these problems.

We will also engage in a practice time library in Java 8 core classes, such as LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Period, Duration and their api.

2. The old time API (before java8) problem

  • Thread-safe - Date and Calendar classes are not thread-safe, making it difficult for developers to debug concurrency issues these api, you need to write extra code to handle thread safety. New Date and Time API Java 8 is introduced immutable and thread-safe, so that these pain points to be addressed.

  • API design and easy to understand - the old time api very difficult to understand, the operation is very complicated, very convoluted, did not provide some common analysis and conversion method. The new API is a time ISO-centric, and follow a consistent domain model date, time, duration and periods of. It provides some very practical ways to support the most common operations. Packaging operations no longer need some time to class ourselves.

  • ZonedDate and Time - to develop in the old time the api must write extra logic to deal with the old API time zone logic, using the new API, you can use Local and ZonedDate / Time API to handle the time zone. Zone conversion problem without too much concern.

3. Use LocalDate, LocalTime and LocalDateTime

The most common type is LocalDate, LocalTime and LocalDateTime. As their name suggests, they represent the local context in combination with the date / time.

These classes are mainly used in the case where it is not necessary explicitly specified context zone. As part of this section, we will introduce the most commonly used API.

3.1. Use LocalDate

LocalDate indicates the date with no specific time in ISO format (YYYY-MM-DD) under.

Often used to indicate the date of birth or the wages of our greatest concern.

Get the current date in the system clock, as follows:

LOCALDATE LOCALDATE = localdate.now ();

 

 

It represents a specific day, month and year LocalDate use "of" method or use "parse" method available. For example, the following code snippet on behalf of 20 February 2015 of LocalDate:

LocalDate.of(2015, 02, 20);
LocalDate.parse("2015-02-20");

 

 

It is not very intuitive and easy to do! LocalDate offers a variety of practical methods to obtain various date information. Let's quickly look at these API methods.

The following code snippet gets the current local date and add the Day:

LocalDate tomorrow = LocalDate.now().plusDays(1);

 

 

This example gets the current date and subtract one month. Notice how it is accepted as an enumeration unit of time:

LocalDate previousMonthSameDay = LocalDate.now().minus(1, ChronoUnit.MONTHS);

 

 

In the following two code samples, we analyzed the date "2016-06-12" and get one day of the week and month, respectively. Note that the return value is the first target of DayOfWeek, while the second is represented by the ordinal value int month:

DayOfWeek sunday = LocalDate.parse("2016-06-12").getDayOfWeek();
int twelve = LocalDate.parse("2016-06-12").getDayOfMonth();

 

 

We can test whether a date occurs in a leap year, if the old way is not to be afraid of God:

boolean leapYear = LocalDate.now().isLeapYear();

 

 

Judgment has date:

boolean notBefore = LocalDate.parse("2016-06-12").isBefore(LocalDate.parse("2016-06-11"));
boolean isAfter = LocalDate.parse("2016-06-12").isAfter(LocalDate.parse("2016-06-11"));

 

 

Date boundaries can be obtained from a given date. In the following two examples, we get LocalDateTime, which represents a given date to start the day (2016-06-12T00: 00) and represents the beginning of LocalDate (2016-06-01):

LocalDateTime beginningOfDay = LocalDate.parse("2016-06-12").atStartOfDay();
LocalDate firstDayOfMonth = LocalDate.parse("2016-06-12")
 .with(TemporalAdjusters.firstDayOfMonth());

 

 

Now let's look at how we use local time.

3.2. Use LocalTime

It represents the time without the date in local time.

Similarly LocalDate and can "parse" and creating LocalTime instance "of" from the system clock or the method used. A quick tour of some of the following common API.

LocalTime may be created from the current instance of the system clock, as follows:

LocalTime now = LocalTime.now();

 

 

In the following code example, we create a representation by parsing the string representation of LocalTime 06:30 AM:

LocalTime sixThirty = LocalTime.parse("06:30");

 

 

Method "of" can be used to create LocalTime. For example, using the following code "of" Method of Creating represents LocalTime 06:30 AM:

LocalTime sixThirty = LocalTime.of(6, 30);

 

 

The following example LocalTime created by parsing a string, and using "plus" API to add one hour. The result will be representatives of 07:30 AM LocalTime:

LocalTime sevenThirty = LocalTime.parse("06:30").plus(1, ChronoUnit.HOURS);

 

 

Various methods can be used to obtain a specific getter unit of time, such as hours, minutes and seconds, obtaining hours as follows:

int six = LocalTime.parse("06:30").getHour();

 

 

LocalDate same as checking whether a specific time in a specific time before or after another. The following code example is a comparison of two LocalTime true:

boolean isbefore = LocalTime.parse("06:30").isBefore(LocalTime.parse("07:30"));

 

 

Maximum, minimum and noon time can be obtained by LocalTime class constants day. When performing a database query to locate a record within a given time frame, which is very useful. For example, the following code representatives of 23: 59: 59.99:

LocalTime maxTime = LocalTime.MAX

 

 

Now let us understand LocalDateTime.

3.3. Use LocalDateTime

The composition LocalDateTime for representing the date and time.

When we need to combine date and time, which is the most common type. This class offers a variety of API, we will introduce some of the most commonly used API.

LocalTime LocalDate and similar examples LocalDateTime acquired from the system clock:

LocalDateTime.now();

 

 

The following code example explains how to use the factory "of" and "parse" method creates an instance. The result will be the representative examples LocalDateTime 2015 Nian 2 Yue 20 Ri 06:30 AM's:

LocalDateTime.of(2015, Month.FEBRUARY, 20, 06, 30);
LocalDateTime.parse("2015-02-20T06:30:00");

 

 

There are some practical computing time API can support specific unit of time, such as days, months, years and minutes. The following code example demonstrates the use of the "plus" and "minus" method. These API's behavior and LocalDate and LocalTime in exactly the same API:

localdatetime.plusdays (1 ); 
localdatetime.minushours ( 2);

 

 

Getter way to extract specific unit like the date and time classes. Given LocalDateTime above example, the following code example returns the month of February:

localDateTime.getMonth();

 

 

4. 使用 ZonedDateTime API

When we need to deal with a specific date and time zone, Java 8 provides ZonedDateTime class. ZoneID is an identifier for representing different regions. About 40 different time zones, using ZoneID represent them, as shown below

The following code we have to get under the "Asia / Shanghai" Time Zone:

ZoneId zoneId = ZoneId.of("Aisa/Shanghai");

 

 

Get all of the time zone:

Set<String> allZoneIds = ZoneId.getAvailableZoneIds();

 

 

LocalDateTime converted to time in a specific time zone:

ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);

 

 

ZonedDateTime provide analytical methods to obtain specific date time zone:

ZonedDateTime.parse("2015-05-03T10:15:30+01:00[Aisa/Shanghai]");

 

 

Another method is to use the time zone OffsetDateTime. Datetime OffsetDateTime having immutable offset representation. Such stores all date and time fields, accurate to nanoseconds and from UTC / Greenwich offset. You can use ZoneOffset create OffsetDateTime instance. Here we create a LocalDateTime to represent the 6:30 February 20, 2015 Morning:

LocalDateTime localDateTime = LocalDateTime.of(2015, Month.FEBRUARY, 20, 06, 30);

 

 

Then we add two hours to set an example by creating LocalDateTime and ZoneOffset:

ZoneOffset offset = ZoneOffset.of("+02:00");
OffsetDateTime offSetByTwo = OffsetDateTime.of(localDateTime, offset);

 

 

Our local date time now is 2015-02-20 06:30 +02: 00. Now let's continue to discuss how to use the Period and the Duration class modification date and time values.

5. Period and Duration

  • Period: for two dates (date) intervals.

  • Duration: two for calculating the time (seconds nanosecond) intervals.

5.1. Use Period

Period classes are widely used to modify the value of a given date or obtaining a difference between the two dates:

LocalDate initialDate = LocalDate.parse("2007-05-10");
LocalDate finalDate = initialDate.plus(Period.ofDays(5));

 

 

There are various classes Period getter methods, such as getYears, getMonths and getDays period from the acquisition target value. The following code example returns an int value of 5, a reverse operation based on the above example:

int five = Period.between(finalDate, initialDate).getDays();

 

 

The Period may be obtained as two days or months between the date or the number of years in a particular cell, using ChronoUnit.between:

int five = ChronoUnit.DAYS.between(finalDate , initialDate);

 

 

This code example returns five days. Let us continue to look at the Duration class.

5.2. Use Duration

Similarly Period, Duration class which is used to handle time. In the following code, we create a 6:30 am local time, and then add a duration of 30 seconds, so that the local time 6:00 am thirty minutes and 30 seconds:

LocalTime initialTime = LocalTime.of(6, 30, 0);
LocalTime finalTime = initialTime.plus(Duration.ofSeconds(30));

 

 

Duration between two moments as duration or get as specific units. In the first code fragment, we used BETWEEN () Method Duration class to find the time difference between the finalTime and initialTime, and returns the difference in seconds:

int thirty = Duration.between(finalTime, initialTime).getSeconds();

 

 

In the second example, we use BETWEEN () method of class ChronoUnit to perform the same operation:

int thirty = ChronoUnit.SECONDS.between(finalTime, initialTime);

 

 

Now let's see how to convert old Date and Calendar for the new Date and Time.

6. Compatibility with date and calendar

Java 8 Added toInstant () method, which helps to convert the old API examples Calendar Date and Time Date new API, as the following code fragment:

LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());

 

 

The LocalDateTime may be constructed from the following "ofEpochSecond" method. The following code would result representative 2016-06-13T11: LocalDateTime 50 to: 34:

LocalDateTime.ofEpochSecond(1465817690, 0, ZoneOffset.UTC);

 

 

Now let's continue with the date and time format.

7. Date and Time Format

Java 8 provides an API for easy formatting dates and times:

LocalDateTime localDateTime = LocalDateTime.of(2015, Month.JANUARY, 25, 6, 30);

 

 

The following code is passed to format the date format ISO local date. The result will be 2015-01-25:

String localDateString = localDateTime.format(DateTimeFormatter.ISO_DATE);

 

 

The DateTimeFormatter offers a variety of standard formatting options. Mode may also provide custom formatting method, as shown below, it will return to LocalDate 2015/01/25:

localDateTime.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));

 

 

We can apply formatting styles are passed to SHORT, LONG MEDIUM or as part of formatting options. The following code sample output lost January 25, 2015 06:30:00 me of:

localDateTime
 .format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
 .withLocale(Locale.UK);

 

 

Finally, let us look at alternative Java 8 Core Date / Time API available.

8. Alternatively

8.1 Threeten library

For Java 6 or Java 7 from these old projects can use Threeten, then, as in the above java 8 use the same function, once you move to java 8 only need to modify your code without changing the package path:

<dependency>
    <groupId>org.threeten</groupId>
    <artifactId>threetenbp</artifactId>
    <version>LATEST</version>
</dependency>

 

 

8.2 Joda-Time library

Another alternative to Java 8 is the date and time library Joda-Time library. In fact, Java 8 Date Time API is led by Joda-Time Library (Stephen Colebourne) and Oracle. The library offers almost all the features of Java 8 Date Time project support. By reference to the following pom dependencies in the project can be used immediately:

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>LATEST</version>
</dependency>

 

Guess you like

Origin www.cnblogs.com/yutf/p/11280775.html