Java Reference
In-Depth Information
The following snippet of code creates some LocalDateTime objects:
// Get the current local datetime
LocalDateTime ldt1 = LocalDateTime.now();
// A local datetime 2012-05-10T16:14:32
LocalDateTime ldt2 = LocalDateTime.of(2012, Month.MAY, 10, 16, 14, 32);
// Construct a local datetime from a local date and a local time
LocalDate ld1 = LocalDate.of(2012, 5, 10);
LocalTime lt1 = LocalTime.of(16, 18, 41);
LocalDateTime ldt3 = LocalDateTime.of(ld1, lt1); // 2012-05-10T16:18:41
Please refer to the online API documentation for these classes for a complete list of methods. Make sure to read
the “Exploring the New Date-Time API” section in this chapter before exploring the online API documentation. You
will find over 60 methods just in one class, LocalDateTime . Without knowing the pattern behind those method names,
looking at the API documentation for these classes will be overwhelming. Remember that you can achieve the same
results using different methods in the API.
Listing 12-7 demonstrates some ways to create and perform operations on a local date, time, and datetime.
Listing 12-7. Using a Local Date, Time, and Datetime
// LocalDateTimeTest.java
package com.jdojo.datetime;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
public class LocalDateTimeTest {
public static void main(String[] args) {
// Create a local date and time
LocalDate ld = LocalDate.of(2012, Month.MAY, 11);
LocalTime lt = LocalTime.of(8, 52, 23);
System.out.println("ld: " + ld);
System.out.println("ld.isLeapYear(): " + ld.isLeapYear());
System.out.println("lt: " + lt);
// Create a local datetime from the local date and time
LocalDateTime ldt = LocalDateTime.of(ld, lt);
System.out.println("ldt: " + ldt);
// Add 2 months and 25 minutes to the local datetime
LocalDateTime ldt2 = ldt.plusMonths(2).plusMinutes(25) ;
System.out.println("ldt2: " + ldt2);
Search WWH ::




Custom Search