How to get milliseconds from LocalDateTime in Java 8
To get the milliseconds from a LocalDateTime
object in Java 8, you can use the toInstant
method and the toEpochMilli
method.
Here's an example of how you can use these methods to get the milliseconds from a LocalDateTime
object:
import java.time.LocalDateTime;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
LocalDateTime localDateTime = LocalDateTime.now();
long milliseconds = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
System.out.println(milliseconds);
}
}
This code defines a LocalDateTime
object and gets the current time using the now
method. It then uses the atZone
method to convert the LocalDateTime
to a ZonedDateTime
object, the toInstant
method to convert the ZonedDateTime
to an Instant
object, and the toEpochMilli
method to convert the Instant
to a long value representing the number of milliseconds since the epoch (midnight, January 1, 1970).
I hope this helps! Let me know if you have any questions.