»
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
1
2
3
4
5
| public static Calendar toCalendar(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
|
»
LocalDate to Calendar
1
2
3
4
5
6
| public static Calendar toCalendar(LocalDate localDate) {
Date date = toDate(localDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
|
»
LocalDateTime to Calendar
1
2
3
4
5
6
| public static Calendar toCalendar(LocalDateTime localDateTime) {
Date date = toDate(localDateTime);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
|
»
Calendar to Date
1
2
3
| public static Date toDate(Calendar calendar) {
return calendar.getTime();
}
|
»
LocalDate to Date
1
2
3
| public static Date toDate(LocalDate dateToConvert) {
return Date.valueOf(dateToConvert);
}
|
»
LocalDateTime to Date
1
2
3
| public static Date toDate(LocalDateTime dateToConvert) {
return new Date(dateToConvert;
}
|
»
Date to LocalDate
1
2
3
| public static LocalDate toLocalDate(Date dateToConvert) {
return new Date(dateToConvert.getTime()).toLocalDate();
}
|
»
Date to LocalDateTime
1
2
3
| public static LocalDateTime toLocalDateTime(Date dateToConvert) {
return new Timestamp(dateToConvert.getTime()).toLocalDateTime();
}
|
»
LocalDate to Timestamp
1
2
3
| public static Timestamp toTimestamp(LocalDate localDate) {
return Timestamp.valueOf(localDate.atStartOfDay());
}
|
»
LocalDateTime to Timestamp
1
2
3
| public static Timestamp toTimestamp(LocalDateTime localDateTime) {
return Timestamp.valueOf(localDateTime);
}
|
»
References
… and probably more sources I haven’t written down :-(