Converting between Date to LocalDate

Learn to convert from java.time.LocalDate to java.util.Date and vice-versa using the easy-to-understand Java examples.

1. Convert Date to LocalDate

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 LocalDate, 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.toLocalDate() method that returns a LocalDate with the same year, month and day as the given Instant.

Date todayDate = new Date();

LocalDate localDate = Instant.ofEpochMilli(todayDate.getTime())
                            .atZone(ZoneId.systemDefault())
                            .toLocalDate();

System.out.println(localDate);  //2022-02-15

2. Convert LocalDate to 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.

LocalDate localDate = LocalDate.now();

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

System.out.println(date); 	//Wed Feb 16 00:00:00 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.

import java.time.LocalDate;
import java.util.Date;

public class Main
{
	public static void main(String[] args)
	{
		Date date = DateUtils.asDate(LocalDate.now());

		System.out.println(date);	

		LocalDate today = DateUtils.asLocalDate(new Date());

		System.out.println(today);
	}
}

Happy Learning !!

Sourcecode on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode