In this example, we show you different ways to convert java.util.Date into java.time.LocalDate.
This is a common task to convert java .util.Date into java.time.LocalDate in Java programming.
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
/**
* Class which shows a way to convert java.util.Date into java.time.LocalDate.
*
* @author sourcecodeexamples.net
*
*/
public class DateToLocalDateConverter {
public static LocalDate convertToLocalDateViaInstant(Date dateToConvert) {
return dateToConvert.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate();
}
public static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert) {
return new java.sql.Date(dateToConvert.getTime()).toLocalDate();
}
public static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert) {
return Instant.ofEpochMilli(dateToConvert.getTime())
.atZone(ZoneId.systemDefault())
.toLocalDate();
}
public static void main(String[] args) {
System.out.println(convertToLocalDateViaInstant(new Date()));
System.out.println(convertToLocalDateViaSqlDate(new Date()));
System.out.println(convertToLocalDateViaMilisecond(new Date()));
}
}
Output:
2019-06-17
2019-06-17
2019-06-17
Reference
Date
Java
Java 8
LocalDate
Comments
Post a Comment