Java date and time
Original link
author : Jakob Jenkov
Translator : Ah for
Table of Contents : http://blog.csdn.net/tjgykhulj/article/details/68952451
(All translators ' comments will appear in this form, and strikethrough lines indicate a disputed or ambiguous place)
A Duration object represents a period of time between two instant and is a new feature added to Java 8.
A duration instance is immutable and cannot be changed after an object is created. You can only create a new Durtaion object by using the duration calculation method. You'll see it later in the tutorial.
Create a Duration instance
Using the Factory method of the duration class to create a duration object, here is an example of using between ():
Instant-Instant.now ();
Wait some time something happens
Instant second = Instant.now ();
Duration Duration = Duration.between (A, second);
time to visit duration
There are two fields in a Duration object: The nanosecond value (the portion less than one second), the second value (a few seconds), and their combination expresses the length of time. Note that when the System.getcurrenttimemillis () is used, the duration does not contain the millisecond attribute.
You can get their values in the following two ways:
Long seconds = getseconds ()
int Nanos = Getnano ()
You can also convert the whole time to other units such as nanoseconds, minutes, hours, days:
Tonanos ()
Tomillis () tominutes () tohours ()
Todays ()
For example: Tonanos () is different from Getnano (), Tonanos () Gets the duration total number of nanoseconds, and Getnano () only gets the portion of the time that is smaller than one second. You may ask why there is no Toseconds () method, because there is already getseconds () This method can achieve the same function.
Duration Calculation
The Duration class contains a series of calculation methods:
Plusnanos ()
Plusmillis () plusseconds () plusminutes ()
plushours
() plusdays () Minusnanos ()
Minusmillis () minusseconds () minusminutes ()
minushours
() minusdays ()
What these methods do is similar, I do not show the internal implementation details here, I would like to show a plus and minus example:
Duration start = ...//obtain a start Duration
Duration Added = start.plusdays (3);
Duration subtracted = start.minusdays (3);
The first line creates a duration object called start, specifically how to create a reference to the preceding code. The 23rd Line sample creates two new duration, which makes the added object represent three days longer than start, and substracted three days less, by invoking the start subtraction operation.
All methods of Calculation return a new duration to ensure the immutable properties of the duration.
Next Chapter: Java.time.LocalDate