Java Reference
In-Depth Information
Adding to or Subtracting from a Date or Calendar
Problem
You need to add or subtract a fixed period to or from a date.
Solution
Create a past or future date by using a locution such as
LocalDate.plus(Period.ofDays(N));
.
Discussion
java.time
offers a
Period
class to represent a length of time, such as a number of days, or
hours and minutes.
LocalDate
and friends offer
plus()
and
minus()
methods to add or sub-
tract a
Period
or other time-related object.
Period
offers factory methods such as
ofDays()
.
The following code computes what the date will be 700 days from now:
import
import
java.time.LocalDate
java.time.LocalDate
;
import
import
java.time.Period
java.time.Period
;
/** DateAdd -- compute the difference between two dates
* (e.g., today and 700 days from now).
*/
public
public class
class
DateAdd
DateAdd
{
public
public static
void
main
(
String
[]
av
) {
/** Today's date */
LocalDate now
=
LocalDate
.
now
();
static
void
Period p
=
Period
.
ofDays
(
700
);
LocalDate then
=
now
.
plus
(
p
);
System
.
out
.
printf
(
"Seven hundred days from %s is %s%n"
,
now
,
then
);
}
}
Running this program reports the current date and time, and what the date and time will be
seven hundred days from now. For example: