Java - Convert Date to LocalDateTime and LocalDateTime to Date
Convert Date to LocalDateTime
The Date.getTime() method returns epoch milliseconds, which are milliseconds elapsed since January 1, 1970 00:00:00 GMT. To get a LocalDateTime, you must first set the zone offset information for the user’s location so that an Instant can be obtained in the specified zone offset.
Then you can use the Instant.toLocalDateTime() method, which returns a LocalDateTime with the same year, month, day, and time as the given Instant on the local timeline.
package com.devkuma.basic.datetime.convert;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class ConvertDateToLocalDateTime {
public static void main(String[] args) {
Date todayDate = new Date();
LocalDateTime localDateTime = Instant.ofEpochMilli(todayDate.getTime())
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
System.out.println(localDateTime);
}
}
Result:
2023-04-17T21:17:05.753
Convert LocalDateTime to Date
You may use this conversion to support some legacy code. In new development code, there is no particular reason to use the Date class.
package com.devkuma.basic.datetime.convert;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class ConvertDateToLocalDateTime {
public static void main(String[] args) {
LocalDateTime localDateTime = LocalDateTime.now();
Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
System.out.println(date);
}
}
Result:
Mon Apr 17 21:16:54 KST 2023
Utility Class
The DateUtils below is a utility class with static methods that convert between Date, LocalDate, and LocalDateTime.
package com.devkuma.basic.datetime.convert;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public final class DateUtils {
private DateUtils() {}
public static Date toDate(LocalDate localDate) {
return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
}
public static Date toDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
public static LocalDate toLocalDate(Date date) {
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
}
public static LocalDateTime toLocalDateTime(Date date) {
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
}
}
To use this utility class, simply call a static method with the correct argument.
package com.devkuma.basic.datetime.convert;
import java.time.LocalDateTime;
import java.util.Date;
public final class UseDateUtils {
public static void main(String[] args) {
Date date = DateUtils.toDate(LocalDateTime.now());
System.out.println(date);
LocalDateTime localDateTime = DateUtils.toLocalDateTime(date);
System.out.println(localDateTime);
}
}