java8 new features seven -Date Time API

Java 8 to further enhance the processing of the date and time by issuing new Date-Time API (JSR 310).

In older versions of Java, there are many problems date and time API, including:

  • Non-thread-safe  - java.util.Date non-thread-safe, all the dates are variable class, which is one of the biggest problems date Java classes.

  • Poor design  - defined Java date / time is not the same class, and in java.util package java.sql class includes the date, in addition to formatting and parsing the class definition java.text package. java.util.Date contains the date and time, and contains only java.sql.Date date will be incorporated into the package java.sql unreasonable. In addition these two classes have the same name, which itself is a very bad design.

  • Time zone handling trouble  - Date class does not offer international, no time zone support, so the introduction of Java and java.util.TimeZone java.util.Calendar class, but they are all above problems also exist.

Java 8 in  java.time  offers many new API under the package. The following are two of the more important API:

  • Local (Local)  - simplifies the handling of date and time, no problem time zone.

  • Zoned (time zone)  - the processing date and time established by time zone.

Java.time new packet covers all the processing date, time, date / time, time zone, time (Instants), the process (During) with the clock (Clock) operation.

 

Java 8 Date / Time class

Java date and time classes 8 contains the LocalDateTime, LocalDate, LocalTime, Instant, Durationand Period, these classes are included in java.timethe package, let's look at the usage of these classes

 

LocalDateTime

LocalDateTimeClass is LocalDateand the LocalTimecombination, can of()create a direct method can invoke LocalDatethe atTime()method or LocalTimethe atDate()method LocalDateor LocalTimecombined into one LocalDateTime:

LocalDateTime ldt1 = LocalDateTime.of(2017, Month.JANUARY, 4, 17, 23, 52);

LocalDate localDate = LocalDate.of(2017, Month.JANUARY, 4);
LocalTime localTime = LocalTime.of(17, 23, 52);
LocalDateTime ldt2 = localDate.atTime(localTime);

LocalDateTimeAlso used to provide LocalDateand LocalTimetransformation:

LocalDate date = ldt1.toLocalDate();
LocalTime time = ldt1.toLocalTime();

 

LocalDatewithLocalTime

 LocalDateClass represents a specific date, specific time, but does not include, nor time zone information. By LocalDatestatic method of()creates an instance, LocalDatealso contains a number of methods used to obtain the year, month, day, day of the week:

Copy the code
LocalDate localDate = LocalDate.of (2017, 1 , 4); // initialize a date: 2017-01-04 
int year = localDate.getYear (); // Year: 2017 
Month = month The localDate.getMonth (); // month: JANUARY 
int dayOfMonth = localDate.getDayOfMonth (); // the first few days of the month: 4 
dayOfWeek dayOfWeek = localDate.getDayOfWeek (); // day of the week: WEDNESDAY 
int length = localDate.lengthOfMonth (); / days / month: 31 
boolean LeapYear = localDate.isLeapYear (); // is a leap year: false
Copy the code

You can also call the static method now()to get the current date:

LocalDate now = LocalDate.now();

 

Instant

InstantFor indicating a timestamp, we often use it System.currentTimeMillis()is somewhat similar, but Instantis accurate to nanoseconds (Nano-Second), System.currentTimeMillis()the method is only accurate to a millisecond (Milli-Second). If you view the Instantsource code and found that its internal use two constants, secondsexpressed from the beginning to the present 1970-01-01 00:00:00 number of seconds, nanosexpressed nanosecond part ( nanosvalue does not exceed 999,999,999). InstantIn addition to the use of now()creation to the methods, but also through ofEpochSecondways to create:

Instant Instant.ofEpochSecond moment = (120, 100,000);

ofEpochSecond()The first parameter is a second method, the second parameter is nanoseconds, after the above code indicates the start 1970-01-01 00:00:00 100 000 ns time of two minutes, the console output :

1970-01-01T00:02:00.000100Z

Duration

DurationInternal implementation and Instantsimilar, but also has two parts: secondsfor seconds, nanosexpressed nanoseconds. The difference is Instantused to represent a time stamp (or a point in time), and Durationrepresents a period of time, so that Durationthe class does not contain now()static methods. You can Duration.between()create a method Durationobjects:

Copy the code
= LocalDateTime.of from the LocalDateTime (2017, Month.JANUARY,. 5, 10,. 7, 0); // 2017-01-05 10:07:00 
the LocalDateTime to LocalDateTime.of = (2017, Month.FEBRUARY,. 5, 10 ,. 7, 0); // 2017-02-05 10:07:00 
the Duration DURATION = Duration.between (from, to); // represents from 2017-01-05 10:07:00 to 2017-02-05 10:07:00 this time 

long days = duration.toDays (); // this time the total number of days of 
long hours = duration.toHours (); // number of hours of the period of 
long minutes = duration.toMinutes () ; // this time the number of minutes 
long seconds = duration.getSeconds (); // this time seconds 
long milliSeconds = duration.toMillis (); // this time milliseconds 
long nanoSeconds = duration.toNanos ( ); // this time the number of nanoseconds
Copy the code

DurationObjects can also of()methods created, which takes a length of time, and a unit of time as a parameter:

Duration duration1 = Duration.of(5, ChronoUnit.DAYS);       // 5天
Duration duration2 = Duration.of(1000, ChronoUnit.MILLIS);  // 1000毫秒

 

Period

PeriodIn concept and Durationsimilar, except that Periodis a date to measure a period of time, such as 2 years and 3 months, 6 days:

Period period = Period.of(2, 3, 6);

PeriodObjects can also between()ways to create, it is worth noting that due Periodis the date measurement period, so between () method can only receive LocalDate types of parameters:

// the period 2017-01-05 to 2017-02-05 
Period = Period.between period ( 
                LocalDate.of (2017,. 1,. 5), 
                LocalDate.of (2017, 2,. 5));

 

And formatting operation date

Increasing and decreasing Date

Java Date / Time class 8 is immutable, it is to ensure thread safety. Of course, the new date / time class also provides a variable version of the method for creating an object, such as adding a day or reducing the Day:

Copy the code
DATE = LocalDate.of the LocalDate (2017,. 1,. 5); // 2017-01-05 

the LocalDate date1 = date.withYear (2016); // modify 2016-01-05 
the LocalDate DATE2 = date.withMonth (2); // modified to 2017-02-05 
LocalDate date3 = date.withDayOfMonth (1); // modified to 2017-01-01 

LocalDate date4 = date.plusYears (1); // increase year 2018-01-05 
LocalDate date5 = date.minusMonths (2); // reduce months 2016-11-05 
the LocalDate date6 date.plus = (. 5, ChronoUnit.DAYS); // increase five days 2017-01-10
Copy the code

The above example is relatively simple for the operation date, but sometimes we have to face a more complex time of the operation, such as the time transferred to the next working day, or the last day of the next month, this time we can use the with()method of another overloaded method that accepts a TemporalAdjusterparameter, can make us more flexible adjustment date:

LocalDate date7 = date.with (nextOrSame (DayOfWeek.SUNDAY )); // returns the next time a distance to the nearest Sunday 
LocalDate date9 = date.with (lastInMonth (DayOfWeek.SATURDAY )); // return the last Saturday of the month

To make the above code compiles correctly, you need to use static import TemporalAdjustersobjects:

import static java.time.temporal.TemporalAdjusters.*;

TemporalAdjustersClass contains many static methods can be used directly, the following table lists some of the ways:

Method name description
dayOfWeekInMonth Returns the day of the week in the same month
firstDayOfMonth Return to the first day of the month
firstDayOfNextMonth Returns the first day of next month
firstDayOfNextYear Return next year on the first day
firstDayOfYear The first day of this year's return
firstInMonth Return to the same month in the first day of the week
lastDayOfMonth Returns the last day of the month
lastDayOfNextMonth The last day to return next month
lastDayOfNextYear The last day to return next year
lastDayOfYear Returns the last day of the year
lastInMonth Return to the same month in the last week
next / previous After a return / before a given day of the week
nextOrSame / previousOrSame After a return / before a given day of the week, if the value meets the conditions for direct return

If the methods listed in the table above can not meet your needs, you can create a custom TemporalAdjusterimplementation of the interface, TemporalAdjusterbut also a function interface, so we can use Lambda expressions:

@FunctionalInterface
public interface TemporalAdjuster {
    Temporal adjustInto(Temporal temporal);
}

Given such a date, the date calculated by the following working day (excluding Saturday and Sunday):

Copy the code
DATE = LocalDate.of the LocalDate (2017,. 1,. 5); 
date.with (temporal -> { 
    // current date 
    dayOfWeek = DayOfWeek DayOfWeek.of (temporal.get (ChronoField.DAY_OF_WEEK )); 

    the // normal circumstances, each second extra day 
    int dayToAdd = 1; 

    // if it is Friday, three additional days 
    IF (dayOfWeek == DayOfWeek.FRIDAY) { 
        dayToAdd = 3; 
    } 

    // If it is Saturday, two additional days 
    if (dayOfWeek == DayOfWeek.SATURDAY) { 
        dayToAdd = 2; 
    } 

    return temporal.plus (dayToAdd, ChronoUnit.DAYS); 
});
Copy the code

 

Date Format

New date API provides a DateTimeFormatterclass for processing date formatting operation, it is included in java.time.formatthe package, Java classes 8 has a date format()a method for date formatted as strings, the method receives DateTimeFormattertype parameters:

LocalDateTime dateTime = LocalDateTime.now();
String strDate1 = dateTime.format(DateTimeFormatter.BASIC_ISO_DATE);    // 20170105
String strDate2 = dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE);    // 2017-01-05
String strDate3 = dateTime.format(DateTimeFormatter.ISO_LOCAL_TIME);    // 14:20:16.998
String strDate4 = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));   // 2017-01-05
String strDate5 = dateTime.format(DateTimeFormatter.ofPattern("今天是:YYYY年 MMMM DD日 E", Locale.CHINESE)); // 今天是:2017年 一月 05日 星期四

Similarly, the date class also supports parse a string into a date object, for example:

String strDate6 = "2017-01-05";
String strDate7 = "2017-01-05 12:30:05";

LocalDate date = LocalDate.parse(strDate6, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime dateTime1 = LocalDateTime.parse(strDate7, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

This place has a pit, java8 DateTimeFormatter can not be resolved in a string date yyyyMMddHHmmssSSS format, reports an error has been fixed in jdk9 years, so here you can Quxianjiuguo, if the incoming string yyyyMMddHHmmssSSS format can be converted to consider their own yyyyMMddHHmmss.SSS format, which is OK. BUG detailed in https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8031085

 

Time zone

Java time zone 8 greatly simplifies the operation, a new time zone class java.time.ZoneIdis the original java.util.TimeZonealternative class. ZoneIdObjects can be ZoneId.of()ways to create, can also ZoneId.systemDefault()default time zone acquisition system:

ZoneId shanghaiZoneId = ZoneId.of("Asia/Shanghai");
ZoneId systemZoneId = ZoneId.systemDefault();

of()Method receives a "region / city" string as a parameter, you can getAvailableZoneIds()get all the legal "area / city" String method:

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

For old time zone class TimeZone, Java 8 also provides a transformation method:

ZoneId oldToNewZoneId = TimeZone.getDefault().toZoneId();

With ZoneId, we can be a LocalDate, LocalTimeor LocalDateTimeobject into ZonedDateTimean object:

Localdateti to localdateti to localdatetime.now = (); 
Zoneddateti to zoneddateti to = zoneddatetime.of (localdateti to, shanghaizoneıd);

The zonedDateTimeprinted to the console:

2017-01-05T15:26:56.147+08:00[Asia/Shanghai]
示例ZonedDateTime
Object consists of two parts, LocalDateTimeand ZoneIdin which 2017-01-05T15:26:56.147part LocalDateTime, +08:00[Asia/Shanghai]part ZoneId.

Another representation is to use time zone ZoneOffset, which is based on the current time and the Universal Time (UTC) / Greenwich Mean Time (GMT) of deviation is calculated, for example:

ZoneOffset zoneOffset = ZoneOffset.of("+09:00");
LocalDateTime localDateTime = LocalDateTime.now();
OffsetDateTime offsetDateTime = OffsetDateTime.of(localDateTime, zoneOffset);

 

Other calendar

Calendar Java is used in ISO 8601 calendar system, which is the world's civil calendar, is what we call the Gregorian calendar. Year has 365 days, leap year is 366 days. The leap year is defined: Non-century years divisible by four; century years divisible by 400. For consistency calculations, the year 1 of the previous year was 2.0 years as AD, and so on.

In addition Java 8 also provides four sets of other calendars (no wonder why people use the Han Chinese lunar calendar), each set contains a calendar date categories, namely:

  • ThaiBuddhistDate: Thai Buddhist calendar
  • MinguoDate: ROC calendar
  • JapaneseDate: Japanese calendar
  • HijrahDate: Islamic calendar

Each class inherits the date of ChronoLocalDatethe class, so it can be operated without knowing the specific calendar. However, these calendars are generally not used, unless there is some special needs will be used for.

These different calendars may also be used to convert the calendar:

LocalDate date = LocalDate.now();
JapaneseDate jpDate = JapaneseDate.from(date);

We in the development process should be avoided if possible ChronoLocalDate, try to use calendar and time-independent manner, because of the way different calculation date calendar is not the same, such as developers will make some assumptions in the program, assuming that there are 12 months in a year if it is included in the Chinese lunar calendar the leap month, one year there may be 13 months, but the developers thought to be 12 months, more than a month out of part of next year. Another example is assumed that the year is cumulative, and after a year plus one, but the Emperor of Japan need to re-dating after generation of the year in the original, so over the years may be counted from 1 year.

It recommended for use in actual development process LocalDate, including interpretation storage, manipulation, business rules; unless the required input or output of the program localization, then you can use ChronoLocalDatethe class.

 

java8 new date api fact, there is not much to say, as a tool category, the best thing to grasp is that it provides a method, known usage scenarios, as well as the known pits.

Reference https://lw900925.github.io/java/java8-newtime-api.html

Guess you like

Origin www.cnblogs.com/wxhbk/p/11612496.html