Home · RSS · E-Mail · GitHub · GitLab · Twitter

Converting Calendar, Date, LocalDate, LocalDateTime and Timestamps in Java

Introduction

Over the years, Java has introduced several packages to deal with any kind of calendar/date/time related stuff. In older and bigger projects, several of those packages may be in use and it can take some work to find a way converting one to another. Here are some helper methods to convert some of them. All of them should be compatible with Java 8.

Date to Calendar

public static Calendar toCalendar(Date date) {
   Calendar calendar = Calendar.getInstance();
   calendar.setTime(date);
   return calendar;
}

LocalDate to Calendar

public static Calendar toCalendar(LocalDate localDate) {
   Date date = toDate(localDate);
   Calendar calendar = Calendar.getInstance();
   calendar.setTime(date);
   return calendar;
}

LocalDateTime to Calendar

public static Calendar toCalendar(LocalDateTime localDateTime) {
   Date date = toDate(localDateTime);
   Calendar calendar = Calendar.getInstance();
   calendar.setTime(date);
   return calendar;
}

Calendar to Date

public static Date toDate(Calendar calendar) {
   return calendar.getTime();
}

LocalDate to Date

public static Date toDate(LocalDate dateToConvert) {
   return Date.valueOf(dateToConvert);
}

LocalDateTime to Date

public static Date toDate(LocalDateTime dateToConvert) {
   return new Date(dateToConvert;
}

Date to LocalDate

public static LocalDate toLocalDate(Date dateToConvert) {
   return new Date(dateToConvert.getTime()).toLocalDate();
}

Date to LocalDateTime

public static LocalDateTime toLocalDateTime(Date dateToConvert) {
   return new Timestamp(dateToConvert.getTime()).toLocalDateTime();
}

LocalDate to Timestamp

public static Timestamp toTimestamp(LocalDate localDate) {
   return Timestamp.valueOf(localDate.atStartOfDay());
}

LocalDateTime to Timestamp

public static Timestamp toTimestamp(LocalDateTime localDateTime) {
   return Timestamp.valueOf(localDateTime);
}

References

… and probably more sources I haven’t written down :-(


Home · RSS · E-Mail · GitHub · GitLab · Twitter