Unix Timestamp in Java
Java 8+ introduced the java.time package (JSR-310) which is the recommended way to work with timestamps. Avoid the old Date and Calendar classes.
Get the current Unix timestamp
Java
import java.time.Instant;
// Recommended (Java 8+)
long seconds = Instant.now().getEpochSecond(); // 1700000000
long millis = Instant.now().toEpochMilli(); // 1700000000000
// Legacy (still works)
long millisLegacy = System.currentTimeMillis();
long secondsLegacy = System.currentTimeMillis() / 1000L;Convert epoch to Instant / LocalDateTime
Java
import java.time.*;
long epoch = 1700000000L;
// To Instant
Instant instant = Instant.ofEpochSecond(epoch);
// To UTC datetime
LocalDateTime utc = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
System.out.println(utc); // 2023-11-14T22:13:20
// To ZonedDateTime with timezone
ZonedDateTime zdt = instant.atZone(ZoneId.of("Asia/Kolkata"));
System.out.println(zdt); // 2023-11-15T03:43:20+05:30[Asia/Kolkata]
// From milliseconds
Instant fromMs = Instant.ofEpochMilli(1700000000000L);Convert LocalDateTime to epoch
Java
import java.time.*;
// From LocalDateTime (specify timezone explicitly)
LocalDateTime ldt = LocalDateTime.of(2023, 11, 14, 22, 13, 20);
long epoch = ldt.toEpochSecond(ZoneOffset.UTC); // 1700000000
// From ZonedDateTime
ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.of("UTC"));
long epoch2 = zdt.toEpochSecond();
// From ISO string
Instant instant = Instant.parse("2023-11-14T22:13:20Z");
long epoch3 = instant.getEpochSecond();Format timestamps
Java
import java.time.*;
import java.time.format.DateTimeFormatter;
Instant instant = Instant.ofEpochSecond(1700000000L);
ZonedDateTime zdt = instant.atZone(ZoneOffset.UTC);
// ISO 8601
DateTimeFormatter.ISO_INSTANT.format(instant); // "2023-11-14T22:13:20Z"
// Custom
zdt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
zdt.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));Time arithmetic
Java
import java.time.*;
Instant now = Instant.now();
Instant future = now.plus(Duration.ofDays(1));
Instant past = now.minus(Duration.ofHours(6));
// Check if expired
Instant expiry = Instant.ofEpochSecond(1700000000L);
if (Instant.now().isAfter(expiry)) System.out.println("expired");→ Use the live epoch converter to convert any Java timestamp instantly.