Java - toXXX( ) Methods

Introduction

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.

The following code has some examples of using toXXX() methods.

Demo

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

public class Main {
  public static void main(String[] args) {
    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.//from   ww w.j a  v a  2s.  c  o m
    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

    System.out.println(ld);
    System.out.println(epochDays);
    System.out.println(ldt);
    System.out.println(lt);
  }
}

Result