Java Convert LocalTime to Epoch Seconds
Tags: Java LocalTime Java 8
Epoch seconds means the number of seconds since the epoch of 1970-01-01T00:00:00Z. In this Java core tutorial we learn how to convert a java.time.LocalTime object with a given LocalDate object into number of epoch seconds.
How to convert LocalTime into Epoch Seconds in Java
With a given LocalTime object in Java, we can use the toEpochSecond() method with a specified LocalDate object and time zone to convert LocalTime to number of epoch seconds as the following example Java code.
ConvertLocalTimeToEpochSecondsExample1.java
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
public class ConvertLocalTimeToEpochSecondsExample1 {
public static void main(String... args) {
int hour = 1;
int minute = 10;
int second = 20;
LocalTime localTime = LocalTime.of(hour, minute, second);
LocalDate today = LocalDate.now();
ZoneOffset offset = ZoneId.systemDefault().getRules().getOffset(Instant.now());
long epochSeconds = localTime.toEpochSecond(today, offset);
System.out.println("LocalTime: " + localTime);
System.out.println("Epoch Seconds: " + epochSeconds);
}
}
LocalTime: 01:10:20
Epoch Seconds: 1650478220
The following Java program to show more example using LocalTime.toEpochSecond() method with UTC time zone.
ConvertLocalTimeToEpochSecondsExample2.java
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneOffset;
public class ConvertLocalTimeToEpochSecondsExample2 {
public static void main(String... args) {
int hour = 1;
int minute = 10;
int second = 20;
LocalTime localTime = LocalTime.of(hour, minute, second);
long epochSeconds = localTime.toEpochSecond(LocalDate.now(), ZoneOffset.UTC);
System.out.println("LocalTime: " + localTime);
System.out.println("Epoch Seconds: " + epochSeconds);
}
}
LocalTime: 01:10:20
Epoch Seconds: 1650503420
Happy Coding 😊
Related Articles
Java Convert LocalTime to String
Java Convert LocalTime to Seconds of Day
Java Convert LocalTime to Nanos of Day
Java Convert LocalTime to LocalDateTime
Java Convert LocalTime to OffsetTime
Java Convert LocalTime to Date
Java Convert LocalTime to Calendar