Convert Java Date to LocalDateTime
In this tutorial, we'll see how we can convert Java Date to LocalDateTime instance.
Here is the brief intro about what is LocalDateTime class in java.
LocalDateTime
- LocalDateTime is an instance of date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.
- LocalDateTime is an immutable date-time object that represents a date-time, often viewed as a year-month-day-hour-minute-second.
There are two ways to convert Java date to LocalDateTime instance.
- Using LocalDateTime ofInstant(Instant instant, ZoneId zone) Method which is taking two parameters Instant instance and ZoneId instance.
- Using ZonedDateTime.toLocalDateTime() method which will be called on Instant object.
As it's clear that we have to convert our java.util.Date first to Instant object then only we can convert Instant object to LocalDateTime object.
Java Date to LocalDateTime
Let's see the above two ways to Convert Java Date to LocalDateTime instance.
1. Using LocalDateTime ofInstant(Instant instant,ZoneId zone)
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class JavaDateToLocalDateTimeExample1 {
public static void main(String[] args) {
// Creating Date Instance
Date today = new Date();
// Creating Instant instance
Instant instant = today.toInstant();
// Getting ZoneId instance
ZoneId systemDefaultZone = ZoneId.systemDefault();
// Creating LocalDateTime instance
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, systemDefaultZone);
System.out.println("Date to LocalDateTime : " + localDateTime);
// Prints : Date to LocalDateTime : 2020-06-27T21:18:53.831
}
}
Output:
Date to LocalDateTime : 2020-06-27T21:18:53.831
2. Using ZonedDateTime.toLocalDateTime() method on Instant object
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class JavaDateToLocalDateTimeExample2 {
public static void main(String[] args) {
// Creating Date Instance
Date today = new Date();
// Getting default timezone instance
ZoneId systemDefaultZone = ZoneId.systemDefault();
// Creating LocalDateTime instance
LocalDateTime localDateTime = Instant.ofEpochMilli(today.getTime())
.atZone(systemDefaultZone).toLocalDateTime();
System.out.println("Date to LocalDateTime : " + localDateTime);
// Prints : Date to LocalDateTime : 2020-06-27T21:18:53.831
}
}
Output:
Date to LocalDateTime : 2020-06-27T21:18:53.831
Conclusion:
In this quick tutorial, we have covered how we can convert Java Date to LocalDateTime instance with System default timezone.
Happy Learning!!!
More Conversion Examples you may like
Comments
Post a Comment
If you have any doubts, Please let me know.