LocalDateTime to Date Conversion in Java [2021]
In this tutorial, we will see how to Convert LocalDateTime to Date in Java. In the earlier tutorial, we have covered how we can Convert LocalDateTime to LocalDate in Java
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 2017-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.
To convert LocalDateTime to date, Date class added one method public static Date from(Instant instant) from 1.8 onwards. so to Convert our LocalDateTime instance to Date we have to first Convert LocalDateTime instance to Instant class object then only we can get Date from LocalDateTime.
LocalDateTime to Date Conversion
Here is the brief information regarding the method
public static Date from(Instant instant)
- This method gets the instance of the Date from an Instant object.
- The instant class can store points on the time in the future in the past than the Date. In this case, this method will throw an exception.
Parameters:
instant - the instant to convert to date.
Returns:
a Date representing the same point on the time-line as the provided instant.
Throws:
NullPointerException is thrown if instant is null.
IllegalArgumentException is thrown if the instant is too large to represent as a Date.
Since:
1.8
Example:
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class LocalDateTimeToDate {
public static void main(String[] args) {
// Creating LocalDateTime instance
LocalDateTime time = LocalDateTime.now();
System.out.println("LocalDateTime value : " + time);
// Creating Instant instance from localDateTime time
Instant instant = time.atZone(ZoneId.systemDefault()).toInstant();
// Creating date from instant instance.
Date date = Date.from(instant);
// Printing date
System.out.println("Date value " + date); // Wed Jul 01 19:34:42 IST 2020
}
}
Output:
LocalDateTime value : 2020-07-01T19:34:42.966
Date value Wed Jul 01 19:34:42 IST 2020
Conclusion:
In this tutorial, we have seen how we can convert LocalDateTime to Date in Java using public static Date from(Instant instant) of Date class.
Comments
Post a Comment
If you have any doubts, Please let me know.