Java – Convert Date to LocalDateTime

Java 8 example to convert Date to LocalDateTime. Also, learn to convert LocalDateTime to Date instance to use in legacy code.

1. Date -> LocalDateTime

Java example to convert from Date to LocalDateTime.

Date todayDate = new Date();

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

System.out.println(ldt); 	//2018-07-15T11:53:31.863

2. LocalDateTime -> Date

Java example to convert from LocalDateTime to Date.

LocalDateTime localDateTime = LocalDateTime.now();

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

System.out.println(date); 	//Sun Jul 15 11:58:26 IST 2018

3. DateUtils class with methods for conversion

Utility class with simple method class to convert between Date and LocalDateTime 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.LocalDateTime;
import java.util.Date;

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

		System.out.println(date);	//Sun Jul 15 12:08:44 IST 2018

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

		System.out.println(today);	//2018-07-15T12:08:44.492
	}
}

Happy Learning !!

References:

  1. LocalDateTime 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.