Java Reference
In-Depth Information
The from( ) Methods
A
from()
method is a static factory method, similar to an
of()
method, that is used to derive a datetime object
from the specified argument. Unlike an
of()
method, a
from()
method requires data conversion on the specified
argument.
To understand what a
from()
method does, think of it named as
deriveFrom()
method. Using a
from()
method,
you derive a new datetime object from the specified argument. The following snippet of code shows how to derive a
LocalDate
from a
LocalDateTime
:
LocalDateTime ldt = LocalDateTime.of(2012, 5, 2, 15, 30); // 2012-05-02T15:30
LocalDate ld = LocalDate.from(ldt); // 2012-05-02
The withXXX( ) Methods
Most classes in the Date-Time API are immutable. They do not have
setXXX()
methods. If you want to change a field
of a datetime object, for example, the year value in a date, you need to look for a method with a prefix like
withXXX
.
A
withXXX()
method returns a copy of an object with the specified field changed.
Assume that you have a
LocalDate
object and you want to change its year. You need to use the
withYear(int newYear)
method of the
LocalDate
class. The following snippet of code shows how to obtain a
LocalDate
from another
LocalDate
with the year changed:
LocalDate ld1 = LocalDate.of(2012, Month.MAY, 2); // 2012-05-02
LocalDate ld2 = ld1.withYear(2014); // 2014-05-02
You can obtain a new
LocalDate
from an existing
LocalDate
by changing multiple fields by chaining the
withXXX()
method calls. The following snippet of code creates a new
LocalDate
from an existing
LocalDate
by
changing the year and month:
LocalDate ld3 = LocalDate.of(2012, 5, 2); // 2012-05-02
LocalDate ld4 = ld3.withYear(2014).withMonth(7); // 2014-07-02
The getXXX( ) Methods
A
getXXX()
method returns the specified element of the object. For example, the
getYear()
method in the
LocalDate
object returns the year part of the date. The following snippet of code shows how to get year, month, and day from a
LocalDate
object:
LocalDate ld = LocalDate.of(2012, 5, 2);
int year = ld.getYear(); // 2012
Month month = ld.getMonth(); // Month.MAY
int day = ld.getDayOfMonth(); // 2
The toXXX( ) Methods
A
toXXX()
method converts an object to a related
XXX
type. For example, the
toLocalDate()
method in the
LocalDateTime
class returns a
LocalDate
object with the date in the object. Below are some examples of using
toXXX()
methods.