Date and time API for Java 8

Source: Internet
Author: User
Tags epoch time time zones new set parse string

This section continues to explore the new features of Java 8, mainly the introduction of Java 8 enhancements to date and time APIs, about dates and times, we've covered two previous sections, and 32 describes the date and time APIs prior to Java 1.8, the main classes are date and calendar, Due to its lack of design, the industry is widely used in a third-party class library joda-time, about Joda-time, we introduced in section 33. Java 1.8 has learned joda-time and introduced a new set of APIs, which are located under Package Java.time, and we will briefly introduce this new API.

Let's start with the date and time representation.

Represents a date and time
Basic concepts
We have introduced several basic concepts of date and time in section 32, which is briefly reviewed here.

    • Moment: All computer systems are represented by an integer, this integer is the number of milliseconds from 0:0 GMT, January 1, 1970, 0 seconds, can understand the moment is absolute time, it is independent of the time zone, different time zones for the same moment of interpretation, that is, date and time is not the same;

    • Time zone: At the same time, different regions of the world may be different times, time and time zone, a total of 24 time zones, the United Kingdom Greenwich is 0 time zone, Beijing is the East eight district, that is, Greenwich 1 o'clock in the morning, Beijing is the morning 9 points;

    • Almanac: We all know that China has the Gregorian and lunar calendar, the Gregorian calendar and the lunar calendar, different calendars, how many months a year, how many days a month, or even how many hours a day, these may not be the same, we mainly discuss the Gregorian calendar.


There are several classes in Java 8 that represent dates and times, mainly:

    • Instant: Indicates the moment, does not correspond directly to the month and day information, need to pass the time zone conversion

    • LocalDateTime: Represents a time zone-independent date and time information that does not correspond directly to the moment and needs to be converted by time zone

    • Localdate: Represents a time zone-independent date, with only date information and no time information compared to LocalDateTime

    • LocalTime: Indicates time zone-independent times, compared to LocalDateTime, only time information, no date information

    • Zoneddatetime: A date and time that represents a specific time zone

    • Zoneid/zoneoffset: Indicates the time zone


The analogy is more, but the concept is clearer, let's look at it one by one.

Instant
Instant represents the moment, gets the current moment, the code is:

Instant now = Instant.now ();


Instant can be created based on Epoch Time (ERA), for example, another code that gets the current moment can be:

Instant now = Instant.ofepochmilli (System.currenttimemillis ());


We know that date also represents a time when instant and date can be converted to each other through eras, for example, converting date to instant, code:

public static Instant toinstant (date date) {
Return Instant.ofepochmilli (Date.gettime ());
}


Convert instant to date and the code is:

public static Date toDate (Instant Instant) {
return new Date (Instant.toepochmilli ());
}


Instant has a lot of time-based comparisons and computational methods, mostly more intuitive, we don't list.

LocalDateTime
LocalDateTime represents date and time information that is independent of the time zone, gets the current date and time for the system default time zone, with the code:

LocalDateTime Ldt = Localdatetime.now ();


You can also use information such as month and date to build localdatetime, for example, the July 11, 2017 20:45 5 seconds, the code can be:

LocalDateTime Ldt = localdatetime.of (2017, 7, 11, 20, 45, 5);


LocalDateTime There are many ways to get calendar information such as date and time of day and month, such as:

public int getYear ()
public int Getmonthvalue ()
public int GetDayOfMonth ()
public int Gethour ()
public int Getminute ()
public int Getsecond ()


You can also get information about the day of the week, such as:

Public DayOfWeek GetDayOfWeek ()


DayOfWeek is an enumeration that has seven values, from Dayofweek.monday to DayOfWeek.Sunday.

LocalDateTime cannot be converted directly to moment instant, the conversion requires a parameter zoneoffset,zoneoffset to indicate a time zone difference relative to Greenwich, and Beijing is +08:00, for example, to convert a localdatetime to Beijing's moment, The method is:

public static Instant tobeijinginstant (LocalDateTime Ldt) {
Return Ldt.toinstant (Zoneoffset.of ("+08:00"));
}


Given a moment, using different time zones to interpret the calendar information is different, instant has a way to return a zoneddatetime according to the time zone:

Public zoneddatetime Atzone (ZoneID zone)


The default time zone is Zoneid.systemdefault (), so you can build ZoneID:

Beijing Time Zone
ZoneID Bjzone = Zoneid.of ("gmt+08:00")


Zoneoffset is a subclass of ZoneID that can be constructed according to the time zone difference.

Localdate/localtime
It can be thought that LocalDateTime is made up of two parts, part of date localdate, the other part is time localtime, and their usage is very intuitive, such as:

Represents July 11, 2017
Localdate ld = localdate.of (2017, 7, 11);


The current time by the system default time zone interpretation of the date
Localdate now = Localdate.now ();

means 21 points, 10 minutes, 34 seconds.
LocalTime lt = localtime.of (21, 10, 34);

Time that is interpreted by the system default time zone at the current time
LocalTime time = Localtime.now ();


LocalDateTime is composed of Localdate and localtime, Localdate plus time can constitute localdatetime,localtime plus date can constitute localdatetime, such as:

LocalDateTime Ldt = localdatetime.of (2017, 7, 11, 20, 45, 5);
Localdate ld = Ldt.tolocaldate (); 2017-07-11
LocalTime lt = Ldt.tolocaltime (); 20:45:05


Localdate plus time, the result is 2017-07-11 21:18:39
LocalDateTime LDT2 = Ld.attime (21, 18, 39);

LocalTime plus date, the result is 2016-03-24 20:45:05
LocalDateTime LDT3 = lt.atdate (Localdate.of (2016, 3, 24));


Zoneddatetime
Zoneddatetime represents the date and time for a specific time zone, gets the current date and time for the system default time zone, with the code:

Zoneddatetime ZDT = Zoneddatetime.now ();


Localdatetime.now () is also the current date and time to get the default time zone, what's the difference? LocalDateTime does not log the time zone information, but only records the date and minute seconds, and so on, and Zoneddatetime in addition to recording calendar information, but also record the time zone, and most of its other building methods need to explicitly pass the time zone, such as:

Build zoneddatetime based on instant and time zones
public static Zoneddatetime ofinstant (Instant Instant, ZoneID Zone)


According to Localdate, localtime and ZoneID structures
public static zoneddatetime of (localdate date, localtime time, ZoneID zone)


Zoneddatetime can be converted directly to instant, for example:

Zoneddatetime Ldt = Zoneddatetime.now ();
Instant now = Ldt.toinstant ();


Format/Parse string
In Java 8, the main format class is Java.time.format.DateTimeFormatter, which is thread-safe and looks at an example:

DateTimeFormatter formatter = Datetimeformatter.ofpattern ("Yyyy-mm-dd HH:mm:ss");
LocalDateTime Ldt = Localdatetime.of (2016,8,18,14,20,45);
System.out.println (Formatter.format (LDT));


The output is:

2016-08-18 14:20:45


To convert a string to a date and time object, you can use the parse method of the corresponding class, such as:

DateTimeFormatter formatter = Datetimeformatter.ofpattern ("Yyyy-mm-dd HH:mm:ss");
String str = "2016-08-18 14:20:45";
LocalDateTime LDT = Localdatetime.parse (str, formatter);


Setting and modification times
There are two ways to modify the period and time, one is to set the absolute value directly, the other is to make relative additions and deletions on the basis of existing values, and most of Java 8 's classes support both, and as with Joda-time, most classes of Java 8 are immutable classes. The modification is done by creating and returning a new object, and the original object itself does not change.

Let's look at some examples.

Adjustment time is 3 o'clock in the afternoon 20
The code example is:

LocalDateTime Ldt = Localdatetime.now ();
LDT = Ldt.withhour (Withminute). Withsecond (0). Withnano (0);


can also be:

LocalDateTime Ldt = Localdatetime.now ();
LDT = Ldt.tolocaldate (). Attime (15, 20);


3 hours five minutes later

The sample code is:

LocalDateTime Ldt = Localdatetime.now ();
LDT = Ldt.plushours (3). Plusminutes (5);


LocalDateTime has many plusxxx and minusxxx methods for relative increases and decreases in time.

Today 0 O'Clock
Can be:

LocalDateTime Ldt = Localdatetime.now ();
LDT = Ldt.with (chronofield.milli_of_day, 0);


Chronofield is an enumeration that defines a number of fields that represent the calendar, Milli_of_day represents the milliseconds in a day, values from 0 to (24 * 60 * 60 * 1,000)-1.

can also be:

LocalDateTime Ldt = Localdatetime.of (Localdate.now (), localtime.min);


Localtime.min means "00:00"

can also be:

LocalDateTime Ldt = Localdate.now (). Attime (0, 0);


Next Tuesday 10 o'clock in the morning full
Can be:

LocalDateTime Ldt = Localdatetime.now ();
LDT = Ldt.plusweeks (1). with (Chronofield.day_of_week, 2)
. with (chronofield.milli_of_day, 0). Withhour (10);


Next Tuesday 10 o'clock in the morning full
The next Tuesday is designated next week, if it is next Tuesday? This is related to the current week, if the current is Monday, then the next Tuesday is tomorrow, and the other case is next week, the code can be:

Localdate ld = Localdate.now ();
if (!ld.getdayofweek (). Equals (Dayofweek.monday)) {
LD = Ld.plusweeks (1);
}
LocalDateTime Ldt = Ld.with (Chronofield.day_of_week, 2). Attime (10, 0);


For this complex tweak, Java 8 has a dedicated interface, Temporaladjuster, which is a functional interface defined as:

Public interface Temporaladjuster {
Temporal adjustinto (temporal temporal);
}


Temporal is an interface that represents a date or time object, Instant,localdatetime,localdate, and so on, and this interface is to adjust the date or time, there is a special class temporaladjusters, It provides a lot of temporaladjuster implementations, for example, for the next week's adjustment, by:

public static Temporaladjuster Next (DayOfWeek DayOfWeek)


For the example above, the code can be:

Localdate ld = Localdate.now ();
LocalDateTime Ldt = Ld.with (Temporaladjusters.next (Dayofweek.tuesday)). Attime (10, 0);


How is this next method implemented? Look at the code:

public static Temporaladjuster Next (DayOfWeek DayOfWeek) {
int dowvalue = Dayofweek.getvalue ();
return (temporal), {
int Caldow = Temporal.get (Day_of_week);
int daysdiff = Caldow-dowvalue;
Return Temporal.plus (Daysdiff >= 0 7-daysdiff:-daysdiff, Days);
};
}


It encapsulates some conditional judgments and specific adjustments within it, providing a more user-friendly interface.

There are many other methods in Temporaladjusters, some of which are as follows:

public static Temporaladjuster Firstdayofmonth ()
public static Temporaladjuster Lastdayofmonth ()
public static Temporaladjuster Firstinmonth (DayOfWeek DayOfWeek)
public static Temporaladjuster Lastinmonth (DayOfWeek DayOfWeek)
public static Temporaladjuster Previous (DayOfWeek DayOfWeek)
public static Temporaladjuster Nextorsame (DayOfWeek DayOfWeek)


These methods are more intuitive and do not explain that they are primarily packaged with some basic operations for date and time adjustments and are more user-friendly.

The last moment of tomorrow
The code can be:

LocalDateTime Ldt = Localdatetime.of (Localdate.now (). Plusdays (1), Localtime.max);


or for:

LocalDateTime Ldt = LocalTime.MAX.atDate (Localdate.now (). Plusdays (1));


Last last day of the month
The code can be:

LocalDateTime Ldt = Localdate.now ()
. with (Temporaladjusters.lastdayofmonth ())
. Attime (Localtime.max);


How is Lastdayofmonth () implemented? Look at the code:

public static Temporaladjuster Lastdayofmonth () {
return (temporal), Temporal.with (Day_of_month, Temporal.range (day_of_month). Getmaximum ());
}


Using the Range method, the maximum minimum value of the corresponding calendar unit can be obtained from its return value, and the last-minute code for the last day of the month can also be:

Long maxdayofmonth = Localdate.now (). Range (Chronofield.day_of_month). Getmaximum ();
LocalDateTime Ldt = Localdate.now ()
. Withdayofmonth ((int) maxdayofmonth)
. Attime (Localtime.max);

The first Monday of the next month, 5 o'clock in the afternoon the whole

The code can be:

LocalDateTime Ldt = Localdate.now ()
. plusmonths (1)
. with (Temporaladjusters.firstinmonth (Dayofweek.monday))
. Attime (17, 0);


Calculation of the time period
Java 8 represents the time period of the class there are two, period and duration,period represents the difference between the date, with the month and day, can not represent the time, duration expressed the difference, with a stopwatch, etc., can also be expressed in days, a day strictly equal to 24 hours, Can not be expressed in years, see some examples below.

Calculates the difference between two dates
Look at an example of period:

Localdate ld1 = Localdate.of (2016, 3, 24);
Localdate ld2 = localdate.of (2017, 7, 12);
Period Period = Period.between (Ld1, ld2);
System.out.println (Period.getyears () + "year"
+ period.getmonths () + "month" + period.getdays () + "Day");


The output is:

1 years March 18 days


Calculate age based on birthday
The sample code can be:

Localdate born = Localdate.of (1990,06,20);
int year = Period.between (born, Localdate.now ()). Getyears ();


Calculate the number of minutes late
Suppose 9 o ' clock in the morning is work time, after 9 o ' clock is late, late to count the number of minutes late, how to calculate? Look at the code:

Long lateminutes = Duration.between (
Localtime.of (9,0),
Localtime.now ()). Tominutes ();


Conversions to Date/calendar objects
The Java 8 date and time API does not provide a way to convert the old Date/calendar to one another, but in practice we may be required, as described earlier, that date can be converted with instant through milliseconds, for other types, and also by milliseconds/ Instant convert each other.

For example, to convert LocalDateTime to date by the default time zone, the code can be:

public static Date toDate (LocalDateTime Ldt) {
return new Date (Ldt.atzone (Zoneid.systemdefault ())
. Toinstant (). Toepochmilli ());
}


To convert Zoneddatetime to calendar, the code can be:

public static Calendar Tocalendar (Zoneddatetime zdt) {
TimeZone TZ = Timezone.gettimezone (Zdt.getzone ());
Calendar calendar = calendar.getinstance (TZ);
Calendar.settimeinmillis (Zdt.toinstant (). Toepochmilli ());
return calendar;
}


The calendar maintains the zoneddatetime time zone information.

To convert date to LocalDateTime in the default time zone, the code can be:

public static LocalDateTime Tolocaldatetime (date date) {
Return Localdatetime.ofinstant (
Instant.ofepochmilli (Date.gettime ()),
Zoneid.systemdefault ());
}


To convert the calendar to Zoneddatetime, the code can be:

public static zoneddatetime tozoneddatetime (Calendar calendar) {
Zoneddatetime ZDT = Zoneddatetime.ofinstant (
Instant.ofepochmilli (Calendar.gettimeinmillis ()),
Calendar.gettimezone (). Tozoneid ());
return ZDT;
}


Summary
This section provides a brief introduction to the date and time APIs in Java 8, which introduces more classes than previous versions of date and calendar, but is clearer, more powerful and easier to use, and Java 8 learns many of the concepts and implementations of joda-time. Much like the joda-time we introduced earlier.

From section 91 to the discussion of lambda expressions to this section, we've covered the main content of Java 8.

At the same time, about the basic part of the entire Java programming, through a total of 95 sections of the content, we also basically discussed, the next section is the final article of this series, we have all 95 sections of the content of a brief comb.

(As with other chapters, all code in this section is located in Https://github.com/swiftma/program-logic, under package shuo.laoma.java8.c95)

Date and time API for Java 8

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.