Java Reference
In-Depth Information
Both LocalDate and LocalTime can be created by parsing a String representing them. You can
achieve this using their parse static methods:
LocalDate date = LocalDate.parse("2014-03-18");
LocalTime time = LocalTime.parse("13:45:20");
It's possible to pass a DateTimeFormatter to the parse method. An instance of this class
specifies how to format a date and/or a time object. It's intended as a replacement for the old
java.util.DateFormat that we mentioned earlier. We show in more detail how you can use a
DateTimeFormatter in section 12.2 . Also note that these parse methods both throw a
DateTimeParseException, which extends RuntimeException in case the String argument can't
be parsed as a valid LocalDate or LocalTime.
12.1.2. Combining a date and a time
The composite class called LocalDateTime pairs a LocalDate and a LocalTime. It represents both
a date and a time, without a time zone, and can be created either directly or by combining a date
and time, as shown in the next listing.
Listing 12.4. Creating a LocalDateTime directly or by combining a date
and a time
// 2014-03-18T13:45:20
LocalDateTime dt1 = LocalDateTime.of(2014, Month.MARCH, 18, 13, 45, 20);
LocalDateTime dt2 = LocalDateTime.of(date, time);
LocalDateTime dt3 = date.atTime(13, 45, 20);
LocalDateTime dt4 = date.atTime(time);
LocalDateTime dt5 = time.atDate(date);
Note that it's possible to create a LocalDateTime by passing a time to a LocalDate, or conversely
a date to a LocalTime, using respectively their atTime or atDate methods. You can also extract
the LocalDate or LocalTime component from a LocalDateTime using the toLocalDate and
toLocalTime methods:
 
Search WWH ::




Custom Search