How to convert a timestamp to a date
Short answer
A Unix timestamp is the number of seconds since January 1, 1970, UTC. Instant.ofEpochSecond() turns it into a moment:
void main() {
Instant instant = Instant.ofEpochSecond(1_772_960_400L);
IO.println(instant);
}Output:
2026-03-08T09:00:00ZTo local time
To get the date and time in a specific zone, add a ZoneId:
void main() {
var dateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(1_772_960_400L), ZoneId.of("Europe/Berlin"));
IO.println(dateTime);
}Output:
2026-03-08T10:00Milliseconds
JavaScript and many APIs give the time in milliseconds — use ofEpochMilli() for them:
void main() {
IO.println(Instant.ofEpochMilli(1_772_960_400_123L));
}Output:
2026-03-08T09:00:00.123ZBack to a number
getEpochSecond() and toEpochMilli() return the timestamp:
void main() {
var moment = LocalDateTime.of(2026, 3, 8, 9, 0).atZone(ZoneOffset.UTC).toInstant();
IO.println(moment.getEpochSecond());
IO.println(moment.toEpochMilli());
}Output:
1772960400
1772960400000Common mistake
Mixing up seconds and milliseconds. Milliseconds passed as seconds give a date tens of thousands of years ahead:
void main() {
long millis = 1_772_960_400_000L;
IO.println(Instant.ofEpochSecond(millis));
IO.println(Instant.ofEpochMilli(millis));
}Output:
+58152-11-17T00:00:00Z
2026-03-08T09:00:00ZFunctions used in this recipe
- Instant — An exact moment on the UTC timeline — for logs, timestamps and measurements.