sneppets-java8

Java 8 – Convert LocalDate to Date ?

Below Java 8 examples shows how to convert from LocalDate to Date and vice versa.

1. LocalDate to Date Example

package com.sneppets.solution;

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

public class LocalDateToDateExample {
	
	public static void main (String[] args) {
		
		LocalDate localDate = LocalDate.now();
		System.out.println("LocalDate now() : " + localDate);
		
		//convert to date from localdate first
		Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
		System.out.println("Date : " + date);
	}

}

Output

LocalDate now() : 2019-11-15
Date : Fri Nov 15 00:00:00 IST 2019

2. Date to LocalDate Example

First convert Date object to Instant instance. Then you need to convert instant instance to LocalDateTime object using default system’s timezone. Finally, use toLocalDate() method of LocalDateTime class to get LocalDate object.

package com.sneppets.solution;

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

public class DateToLocalDateExample {
	
	public static void main (String[] args) {
		
		//today date
		Date date = new Date();		
		System.out.println("Today's Date : " + date);
		//convert Date object to Instant 
		Instant instant = Instant.ofEpochMilli(date.getTime());
                //convert Instant to LocalDateTime object
		LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
		LocalDate localDate = localDateTime.toLocalDate();
		System.out.println("LocalDate: " + localDate);
		
	}

}

Output

Today's Date : Fri Nov 15 19:37:03 IST 2019
LocalDate: 2019-11-15

Further Learning

References

guest
0 Comments
Inline Feedbacks
View all comments