10

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

 3 years ago
source link: https://sj14.gitlab.io/post/2019/07-03-java-calendar-date-timestamp/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
2019-07-03

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 :-(


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK