The source code is for testing only and should not be used commercially. The source code comes from the Internet. If there is any infringement, please contact me to remove it.
Java 8 Time Api 使用指南 珍藏版

1. overview

Java 8 introduces new APIs for Date and Time to solve the problem of oldjava.util.Dateandjava.util.Calendarshortcomings. As part of this article, let's start by looking at some of the issues with existing Date and Calendar APIs and explore how the new Java 8 Date and Time APIs solve these issues. We will also work on core classes in the Java 8 Time Class Library, such asLocalDate, LocalTime, LocalDateTime, ZonedDateTime, Period, Durationand their apis.

2. Problems with the old time API (before java8)

  • thread-safe– Date andCalendarClasses are not thread-safe, making it difficult for developers to debug concurrency issues in these APIs and requiring additional code to be written to handle thread safety. The new Date and Time APIs introduced in Java 8 are immutable and thread-safe, allowing these pain points to be addressed.
  • API design and easy-to-understand Old time APIs are very difficult to understand, very complex to operate, very round-about, and do not provide some commonly used parsing and conversion methods. The new time API is ISO-centric and follows a consistent domain model of date, time, duration and periods. Provides some very practical methods to support the most common operations. We no longer need to encapsulate some time operation classes ourselves and describe them semantically.
  • ZonedDate and Time In the old time api, developers had to write additional logic to handle the time zone logic of the old API, while with the new API, they could use the Local and ZonedDate / Time APIs to handle the time zone. Don't worry too much about time zone conversion issues.

3. Using LocalDate, LocalTime and LocalDateTime

The most commonly used classes areLocalDateLocalTimeandLocalDateTime。As their name suggests, they represent the local date/time combined with the context.
These classes are mainly used when you do not need to explicitly specify the time zone in the context. As part of this section, we will introduce the most commonly used APIs.

3.1 Using LocalDate

LocalDateRepresents in ISO format (YYYY-MM-DD) without specific time. Often used to indicate birthdays or the date we care about most about when we are paid. Get the date under the current system clock, as follows:
LocalDate localDate = LocalDate.now();
LocalDate representing specific days, months and years can be obtained using the "of" method or using the "parse" method. For example, the following code fragment represents LocalDate on February 20, 2015:
LocalDate.of(2015, 02, 20); LocalDate.parse("2015-02-20");
Is it very intuitive and convenient! LocalDate provides various practical methods to obtain various date information. Let's take a quick look at these API methods. The following code snippet gets the current local date and adds a day:
LocalDate tomorrow = LocalDate.now().plusDays(1);
This example takes the current date and subtracts one month. Notice how it accepts enumerations as units of time:
LocalDate previousMonthSameDay = LocalDate.now().minus(1, ChronoUnit.MONTHS);
In the following two code examples, we analyze the date "2016-06-12" and get the day of the week and the day of the month respectively. Notice the return values, the first one is the object that represents DayOfWeek, and the second one is the int that represents the ordinal value of the month:

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

We can also test whether a date occurs in a leap year. If we use the old method, we may not be going to heaven:
boolean leapYear = LocalDate.now().isLeapYear();
Determine the order of dates:

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

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

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

Now let's take a look at how we use local timeLocalTime

3.2 Using LocalTime

Represents time without date in local time. withLocalDateSimilarly, you can create LocalTime instances from the system clock or using the "parse" and "of" methods. A quick look at some of the commonly used APIs below. You can create an instance of the current LocalTime from the system clock, as follows:
LocalTime now = LocalTime.now();
In the following code example, we create aLocalTime
LocalTime sixThirty = LocalTime.parse("06:30");
Method "of" can be used to createLocalTime。For example, the following code uses the "of" method to create aLocalTime
LocalTime sixThirty = LocalTime.of(6, 30);
The following example is created by parsing a stringLocalTime, and add it for an hour using the "plus" API. The result will be a representative of 07:30 AMLocalTime
LocalTime sevenThirty = LocalTime.parse("06:30").plus(1, ChronoUnit.HOURS);
Various getter methods can be used to get specific units of time, such as hours, minutes, and seconds, and get hours as follows:
int six = LocalTime.parse("06:30").getHour();
withLocalDateAlso check whether a specific time is before or after another specific time. The following code example compares the results as followstruethe twoLocalTime
boolean isbefore = LocalTime.parse("06:30").isBefore(LocalTime.parse("07:30"));
The maximum, minimum and noon times of the day can be obtained from constants in the LocalTime class. This is useful when performing database queries to find records within a given time range. For example, the following code represents23:59:59.99
LocalTime maxTime = LocalTime.MAX;
Now let's take a deeper look atLocalDateTime

3.3 Using LocalDateTime

The LocalDateTime is used to represent a combination of date and time. This is the most commonly used class when we need to combine date and time. This class provides various APIs, and we will introduce some of the most commonly used APIs. similar toLocalDateandLocalTimeObtained from system clockLocalDateTimeExamples of:
LocalDateTime.now();
The following code example explains how to create an instance using the factory "of" and "parse" methods. The result will be representativeFebruary 20, 2019 06:30 AM theLocalDateTimeExample:

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

There are some practical APIs that support time calculations for specific units of time, such as days, months, years, and minutes. The following code example demonstrates the use of the Add and Subtract methods. The behavior of these APIs is related toLocalDateandLocalTimeThe APIs in are exactly the same:

localDateTime.plusDays(1);
localDateTime.minusHours(2);

The Getter method can be used to extract specific units similar to date and time classes. in view of the aboveLocalDateTimeExample, the following code example will return the month of February:
localDateTime.getMonth();

4. Using the ZonedDateTime API

When we need to deal with time zone specific dates and times, Java 8 providesZonedDateTimeClass. ZoneID is an identifier used to represent different areas. There are about 40 different time zones, usingZoneIDRepresents them as follows
Let's get the following code"Asia/Shanghai"Time zone:
ZoneId zoneId = ZoneId.of("Aisa/Shanghai");
Get all time zones:
Set<String> allZoneIds = ZoneId.getAvailableZoneIds();
LocalDateTimeConvert to time in a specific time zone:
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
ZonedDateTime provides parsing methods to obtain specific date and time in the time zone:
ZonedDateTime.parse("2019-06-03T10:15:30+01:00[Aisa/Shanghai]");
Another way to use time zones is to use theOffsetDateTimeOffsetDateTimeIs an immutable representation of date and time with an offset. This class stores all date and time fields, accurate to nanoseconds, and offsets from UTC/Greenwich. may be usedZoneOffsetcreateOffsetDateTimeExamples. Here we create aLocalDateTimerepresentedFebruary 20, 2015 at 6:30 am
LocalDateTime localDateTime = LocalDateTime.of(2019, Month.FEBRUARY, 20, 06, 30);
And then we createdZoneOffsetand forLocalDateTimeExample settings to add two hours:

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

We now assume that the local date and time is2019-02-20 06:30 +02:00。Now let's continue discussing how to usePeriodandDurationClass modifies the date and time values.

5. Use Period and Duration

  • Period : Used to calculate the interval between two dates (year, month, year).
  • Duration : Used to calculate two time intervals (seconds, nanoseconds).

5.1 Use Period

Period Class is widely used to modify the value of a given date or get the difference between two dates:

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

Period Class has various getter methods, such asgetYearsgetMonthsandgetDaysGets the value cycle object from. The following code example returns aintA value of 5 is based on the reverse order operation in the above example:
int five = Period.between(finalDate, initialDate).getDays();
thePeriod You can obtain data such as days or months or years between two dates in a specific unit, using theChronoUnit.between
int five = ChronoUnit.DAYS.between(finalDate , initialDate);
This code example returns five days. Let's keep lookingDurationClass.

5.2 Use Duration

similarPeriodDurationClass is used to process time. In the following code, we create a local time of 6:30 a.m., and then add a duration of 30 seconds to make the local time of 6:30 a.m.:

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

The duration between two moments can be obtained as a duration or as a specific unit. In the first code fragment, we useDurationclassbetween()way to findfinalTimeandinitialTimeand returns the difference in seconds:
int thirty = Duration.between(finalTime, initialTime).getSeconds();
In the second example, we useChronoUnitclassbetween()Method to perform the same operation:
int thirty = ChronoUnit.SECONDS.between(finalTime, initialTime);
Now let's take a look at how to put the oldDate andCalendar converted to the newDateandTime

6. Compatibility with dates and calendars

Java 8 addedtoInstant()Method, which helps convert Date and Calendar instances from the old API to the new Date Time API, as shown in the following code fragment:

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

theLocalDateTimeIt can be constructed from the following "ofEpochSecond" method. The result of the following code will be a representative2019-06-13T11:34:50 theLocalDateTime
LocalDateTime.ofEpochSecond(1465817690, 0, ZoneOffset.UTC);
Now let's continue with date and time formatting.

7. Date and time formatting

Java 8 provides APIs for easily formatting dates and times:
LocalDateTime localDateTime = LocalDateTime.of(2019, Month.JANUARY, 25, 6, 30);
The following code passes the ISO date format to format the local date. result will be2019-01-25
String localDateString = localDateTime.format(DateTimeFormatter.ISO_DATE);
theDateTimeFormatterVarious standard format options are available. You can also provide a custom pattern to format the method. Customize the above example as shown below, and it will returnLocalDatefor2019/01/25
localDateTime.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
We can pass the format style asSHORTLONGorMEDIUMAs part of the formatting options. The following code example will be displayed in theJanuary 25, 2019 06:30:00 Give a representationLocalDateTimeOutput of:
localDateTime.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withLocale(Locale.UK);
Finally, let's take a look at the alternatives available to the Java 8 Core Date / Time API. Not all projects use Java 8.

8. alternative

8.1 Using the Threeten class library

For older projects from Java 7 or Java 6, you can use Threeten , and then you can use the same functionality as in Java 8 above. Once you migrate to Java 8, you only need to modify your package path code without changing it. You can use it immediately by referencing the following pom dependencies in your project:

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

8.2 Joda-Time class library

Another alternative to the Java 8 date and time library is the veteran time processing class library Joda-Time. In fact, the Java 8 Date Time API absorbs a large number of Joda-Time libraries. This library provides almost all the features supported in the Java 8 Date Time project. You can use it immediately by referencing the following pom dependencies in your project:

<dependency>    
   <groupId>joda-time</groupId>    
   <artifactId>joda-time</artifactId>    
   <version>LATEST</version>
</dependency>
read more
Resource download
PriceFree
The use is limited to testing, experiments, and research purposes. It is prohibited for all commercial operations. This team is not responsible for any illegal behavior of users during use. Please self-test all source codes! There is no guarantee of the integrity and validity of your source code. All source code is collected from the entire network
Original link:https://bcbccb.cn/en/3141.html, please indicate the source for reprinting. Disclaimer: This resource has not been authorized by the original rights holder and is not commercially available. It can only be used to learn and analyze the underlying code, CSS, etc., and is prohibited for commercial purposes. Any relevant disputes and legal liabilities arising from unauthorized commercial use shall be fully borne by the user. Everyone is responsible to support genuine copies. Please delete them within 24 hours after downloading. Thank you for your support!
1

Comments0

情怀数据库备份文件
Feelings database backup files
Someone bought it 6 minutes ago Go and have a look

Site Announcements

The source code (theme/plug-in/application source code) and other resources provided by this site are only for learning and exchange

Commercial use is prohibited, otherwise all consequences will be borne by the downloading user!

Some resources are collected or copied online. If they infringe on your legitimate rights and interests, please write to us.

Currently, members have a big reward, and the current price for a lifetime member is 299 gold coins.Recent price adjustments

Join quickly, opportunities wait for no one! immediately participated in

Captcha

Fast login to social accounts

en_USEnglish