The Java 8
java.time API provides
LocalDateTime classes to represent date-time values.
The main difference would be
Instant represents a date-time value with precision to nanoseconds in UTC time-zone and whereas the
LocalDateTime represent the date-time without time-zone.
In this tutorial, you will learn about what is Java 8 Instant and LocalDateTime in detail.
The Java 8 Instant returns a current time calculated based on the Epoch seconds since
Instant will return UTC time by calculating the offset difference with the current system time.
Instant for applications requiring exact time, like System timestamps and time difference calculations.
Check this tutorial to convert a Date to Instant, How to convert an Instant to date format in Java.
import java.time.Instant; //current UTC Time : 20 Feb 2023 T 19:02:46 //current system timezone : Australia/Sydney, current date : 21 Feb 2023, current time: 06:02:46 //main Instant instant = Instant.now(); System.out.println(instant); //2023-02-20T19:02:46.789023900Z
In the above example, The system time zone is “Australia/Sydney”, which is +11:00 hours from UTC. Instant return time zone independent value matches the UTC time(2023-02-20T19:02:46.789023900Z) 11:00 hours behind the system time. Instant always calculates time-based on the offset difference with the current system time zone to match the UTC time.
The Java 8 LocalDateTime represent only date and time without any reference to the time zone. The LocalDateTime value can be converted to Instant if the time zone is known.
To convert LocalDateTime to Instant, check this tutorial, How to convert an Instant to Java 8 LocalDateTime.
LocalDateTime for scenarios to represent only date-time without a time zone. It will return the date-time based on the system time zone.
import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; //current UTC Time : 20 Feb 2023 T 19:02:46 //current system timezone : Australia/Sydney, current date : 21 Feb 2023, current time: 06:02:46 //main LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDateTime); //2023-02-21T06:02:46.872677100
In the above example, LocalDateTime returns the date-time(2023-02-21T06:02:46.872677100) value without the time zone. The date-time calculation is based on the system time zone (Australia/Sydney).
To convert an milliseconds to LocalDateTime value, read this article; How to convert long Epoch time in Milliseconds to Java 8 LocalDateTime.