Java Reference
In-Depth Information
LocalDate ld = LocalDate.of(2012, 5, 2); // 2012-05-02
// Convert the date to epoch days. The epoch days is the number of days from
// 1970-01-01 to a date. A date before 1970-01-01 returns a negative integer.
long epochDays = ld.toEpochDay(); // 15462
// Convert a LocalDateTime to a LocalTime using the toLocalTime() method
LocalDateTime ldt = LocalDateTime.of(2012, 5, 2, 15, 50);
LocalTime lt = ldt.toLocalTime(); // 15:50
The atXXX( ) Methods
An
atXXX()
method lets you build a new datetime object from an existing datetime object by supplying some
additional pieces of information. Contrast the use of an
atXXX()
method with that of a
withXXX()
method; the former
lets you create a new type of object by providing additional information whereas the latter lets you create a copy of an
object by changing its fields.
Suppose you have the date 2012-05-02. If you want to create a new date of 2012-07-02 (with month changed to 7),
you would use a
withXXX()
method. If you want to create a datetime of 2012-05-02T15:30 (by adding time 15:30),
you would use an
atXXX()
method. Some examples of using
atXXX()
methods are shown below.
LocalDate ld = LocalDate.of(2012, 5, 2); // 2012-05-02
LocalDateTime ldt1 = ld.atStartOfDay(); // 2012-05-02T00:00
LocalDateTime ldt2 = ld.atTime(15, 30); // 2012-05-02T15:30
The
atXXX()
methods supports the builder pattern. The following snippet of code shows how to use a builder
pattern to build a local date:
// Use a builder pattern to build a date 2012-05-22
LocalDate d1 = Year.of(2012).atMonth(5).atDay(22);
// Use an of() factory method to build a date 2012-05-22
LocalDate d2 = LocalDate.of(2012, 5, 22);
The plusXXX( ) and minusXXX( ) Methods
A
plusXXX()
method returns a copy of an object by adding a specified value. For example, the
plusDays(long days)
method in the
LocalDate
class returns a copy of the
LocalDate
object by adding the specified number of days.
A
minusXXX()
method returns a copy of an object by subtracting a specified value. For example, the
minusDays(long days)
method in the
LocalDate
class returns a copy of the
LocalDate
object by subtracting the
specified number of days.
LocalDate ld = LocalDate.of(2012, 5, 2); // 2012-05-02
LocalDate ld1 = ld.plusDays(5); // 2012-05-07
LocalDate ld2 = ld.plusMonths(3); // 2012-08-02
LocalDate ld3 = ld.plusWeeks(3); // 2012-05-23
LocalDate ld4 = ld.minusMonths(7); // 2011-10-02
LocalDate ld5 = ld.minusWeeks(3); // 2012-04-11