Java – Convert Date to LocalDate

Java example to convert LocalDate to Date and vice-versa.

1. Convert Date to LocalDate

Java example to convert from Date to LocalDate.

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

System.out.println(localDate); 	//2018-07-15

2. Convert LocalDate to Date

Java example to convert from LocalDate to Date. I will recommend using LocalDate class. Use this conversion to support some legacy technical debt only.

LocalDate localDate = LocalDate.now();

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

System.out.println(date); 	//Sun Jul 15 00:00:00 IST 2018

3. DateUtils Class having methods for conversion

Utility class with simple method class to convert between Date and LocalDate variants.

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();
	}
}

3.1. How to use

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);	//Sun Jul 15 00:00:00 IST 2018

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

		System.out.println(today);	//2018-07-15
	}
}

Happy Learning !!

References:

  1. LocalDate Javadoc
  2. ZoneId Javadoc
  3. Date Javadoc

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.