Convert between Date to LocalDateTime

Learn to convert java.util.Date to java.time.LocalDateTime and vice versa using easy-to-understand Java programs.

1. Date -> LocalDateTime

The Date.getTime() method returns the epoch milliseconds i.e. the number of milliseconds since January 1, 1970, 00:00:00 GMT. To get the LocalDateTime, we need to first set the zone offset information of the user location to get the Instant at specified zone offset.

Then we can use Instant.toLocalDateTime() method that returns a LocalDateTime with the same year, month, day and time as the given Instant in the local timeline.

Date todayDate = new Date();

LocalDateTime ldt = Instant.ofEpochMilli( todayDate.getTime() )
							.atZone( ZoneId.systemDefault() )
							.toLocalDateTime();

System.out.println(ldt); 	//2022-01-15T11:53:31.863

2. LocalDateTime -> Date

We can need to use this conversion to support some legacy technical debt only. There is no reason to use the Date class in the new development code.

LocalDateTime localDateTime = LocalDateTime.now();

Date date = Date.from(localDateTime.atZone( ZoneId.systemDefault() ).toInstant());

System.out.println(date); 	//Sat Jan 15 11:58:26 IST 2022

3. Utility Methods

The DateUtils is a utility class with some static methods to convert between Date, LocalDate and LocalDateTime.

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class DateUtils {

	public static Date asDate(LocalDate localDate) {
		return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
	}

	public static Date asDate(LocalDateTime localDateTime) {
		return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
	}

	public static LocalDate asLocalDate(Date date) {
		return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
	}

	public static LocalDateTime asLocalDateTime(Date date) {
		return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
	}
}

To use this class, simply invoke the static methods and pass the correct argument.

Date date = DateUtils.asDate(LocalDateTime.now());

System.out.println(date);   //Sat Jan 15 12:08:44 IST 2022

LocalDateTime today = DateUtils.asLocalDateTime(new Date());

System.out.println(today);  //2022-01-15T12:08:44.492

Happy Learning !!

Sourcecode on Github

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.