Java - Create and perform operations on a local date, time, and datetime.

Description

Create and perform operations on a local date, time, and datetime.

Demo

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;

public class Main {
  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 date time 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 date time
    LocalDateTime ldt2 = ldt.plusMonths(2).plusMinutes(25);
    System.out.println("ldt2: " + ldt2);

    // Derive the local date and time from the local date time
    LocalDate ld2 = LocalDate.from(ldt2);
    LocalTime lt2 = LocalTime.from(ldt2);
    System.out.println("ld2: " + ld2);
    System.out.println("lt2: " + lt2);
  }//from   w  w  w.  j  a v  a2 s  . c  om
}

Result

Related Topic