Java Date convert to LocalTime

Description

Java Date convert to LocalTime

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;

public class Main {
  public static void main(String[] argv) {
    /*  ww w.  j a va  2s .c om*/
     LocalTime lt = dateToLocalTime(new Date()); 
     System.out.println(lt);
  }
  /**
   * Converts the specified Date object to LocalTime.
   *
   * @param date
   *          Date object containing the date
   * @return the created LocalTime (JSR 310)
   */
  public static LocalTime dateToLocalTime(final Date date) {
    return dateToLocalDateTime(date).toLocalTime();
  }
  /**
   * Converts the specified Date object to LocalDate.
   *
   * @param date
   *          Date object containing the date
   * @return the created LocalDate (JSR 310)
   */
  public static LocalDate dateToLocalDate(final Date date) {
    return dateToLocalDateTime(date).toLocalDate();
  }

  /**
   * Converts the specified Date object to LocalDateTime.
   *
   * @param date
   *          Date object containing the date and time
   * @return the created LocalDateTime (JSR 310)
   */
  public static LocalDateTime dateToLocalDateTime(final Date date) {
    final Instant instant = Instant.ofEpochMilli(date.getTime());
    return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
  }
}



PreviousNext

Related