Close

Java - How to convert Calender to LocalDateTime?

[Updated: Mar 5, 2018, Created: Apr 28, 2017]

Java Date Time Java 

In this quick example, we will show how to convert java.util.Calender to java.time.LocalDateTime


import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.TimeZone;

public class CalenderToLocalDateTimeExample {

  public static LocalDateTime toLocalDateTime(Calendar calendar) {
      if (calendar == null) {
          return null;
      }
      TimeZone tz = calendar.getTimeZone();
      ZoneId zid = tz == null ? ZoneId.systemDefault() : tz.toZoneId();
      return LocalDateTime.ofInstant(calendar.toInstant(), zid);
  }

  public static void main(String[] args) {
      Calendar now = Calendar.getInstance();
      LocalDateTime localDateTime = toLocalDateTime(now);
      System.out.println(localDateTime);
  }
}

Output

2018-03-05T14:23:35.466

See Also