Preslav's Thoughts and Ramblings

A Simple Util Class for Converting Between Date and LocalDate

11 October 2015 | java

There is no direct way to convert between Java's traditional Date API, and the more modern LocalDate one, which came with Java 8. Ever since I started working withe the new date APIs in Java 8, I have been trying to use them exclusively in the majority of my code (I have the privilege to work with Java 8 in all of my projects). Unfortunately, most of the def-facto standard libraries are still stuck somewhere between java 5 and 6, so an elegant way to convert between Date and LocalDate was needed. Luckily, I found this piece of code, which gave me some initial directions. It can, and most probably should, be extended with further functions, but it is a good start. Hope, it helps you too.

public class DateUtils {

  public static Date asDate(LocalDate localDate) {
    return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
  }

  public static Date asDate(LocalDateTime localDateTime) {
    return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
  }

  public static LocalDate asLocalDate(Date date) {
    return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
  }

  public static LocalDateTime asLocalDateTime(Date date) {
    return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
  }
}