Java Convert LocalDateTime to Epoch Seconds

Tags: Java LocalDateTime Java 8

In this Java core tutorial we learn how to convert a LocalDateTime object to an epoch seconds value in Java programming language.

How to convert LocalDateTime to Epoch Seconds in Java

In Java, with a given LocalDateTime object we can use the LocalDateTime.toEpochSecond(ZoneOffset offset) method to convert it to an epoch seconds value which is the number of seconds from the epoch of 1970-01-01T00:00:00Z as the example Java code below.

ConvertLocalDateTimeToEpochSecondsExample1.java

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;

public class ConvertLocalDateTimeToEpochSecondsExample1 {
    public static void main(String... args) {
        LocalDateTime localDateTime = LocalDateTime.parse("2022-05-19T08:30:55");

        ZoneOffset zoneOffset = ZoneId.systemDefault().getRules().getOffset(Instant.now());

        long epochSeconds = localDateTime.toEpochSecond(zoneOffset);

        System.out.println("LocalDateTime: " + localDateTime);
        System.out.println("Epoch Seconds: " + epochSeconds);
    }
}
The output as below.
LocalDateTime: 2022-05-19T08:30:55
Epoch Seconds: 1652923855

Happy Coding 😊

Java Convert LocalDateTime to Instant

Java Convert LocalDateTime to String

Java Convert LocalDateTime to LocalDate

Java Convert LocalDateTime to LocalTime

Java Convert LocalDateTime to OffsetDateTime

Java Convert LocalDateTime to ZonedDateTime

Java Convert LocalDateTime to Calendar

Java Convert LocalDateTime to Date

Java LocalDateTime by Examples

Java Convert Epoch Seconds to LocalDateTime