Java Instant and epoch seconds

One number, three java.time classes and one classic 1000× bug. Convert an epoch value below, then read how Instant, OffsetDateTime and ZonedDateTime divide the work — and when ofEpochSecond is right and ofEpochMilli is wrong.

[MOD.CONV // INSTRUMENT]

UNIX TIMESTAMP INPUT

Auto-detects seconds, ms, µs, ns

Date output is floored to milliseconds. Choose a unit explicitly for older dates or values outside auto-detection.

Typical today: 10 (s), 13 (ms), 16 (µs), 19 (ns) digits. A unit heuristic, not a definition.

01 Local time —
02 UTC standard —
03 ISO 8601 —
04 Relative —
[SUB.REVERSE]
SECONDS (S) —
MILLISECONDS (MS) —

Local means your device timezone. During a repeated daylight-saving hour, the earlier occurrence is used; use UTC to choose an unambiguous instant.

Browser-side reference calculator. It does not execute Java, Go, PHP or shell commands; use the examples below in your own runtime.

[SEC.02 // THE THREE CLASSES]

Instant, OffsetDateTime and ZonedDateTime

SPLIT BY ZONE KNOWLEDGE

java.time splits "a moment in time" from "what the wall clock said" across three classes. They are views of the same instant at three levels of zone information:

ClassHoldsZone knowledgeBuilt for
InstantSeconds + nanos since 1970-01-01T00:00:00ZNone — UTC by contractStoring and comparing moments: logs, DB columns, API fields
OffsetDateTimeDate-time plus one fixed offset such as +02:00A single fixed offset, no rulesSerializing with an explicit offset, RFC 3339 style
ZonedDateTimeDate-time plus an IANA ZoneId like Europe/BerlinFull historical and DST rulesWall-clock scheduling for humans

Within the destination date-time range, instant.atZone(zone) and instant.atOffset(offset) preserve the instant, and toInstant() returns it without precision loss. Instant has a wider range: values near Instant.MIN or Instant.MAX can throw when converted to a zoned or offset date-time. For supported values, only the local reading changes. That is the code-level version of why a Unix timestamp never contains a timezone: the zone appears when a human looks.

[SEC.03 // THE 1000× TRAP]

ofEpochSecond vs ofEpochMilli

PICK BY SOURCE UNIT

Both factory methods take a long and both return an Instant — the only difference is the unit they assume. Mixing the units often produces a valid but wrong date; sufficiently large seconds or adjustments can instead throw a range or arithmetic exception:

The number came fromCallWhy
System.currentTimeMillis()Instant.ofEpochMilli(ms)The JDK hands you milliseconds here — pass them on unchanged
An epoch-seconds DB column, getEpochSecond(), log parsersInstant.ofEpochSecond(s)Those are seconds; ofEpochMilli would push the date back into January 1970
Seconds plus a sub-second partInstant.ofEpochSecond(s, nanoAdjustment)The adjustment is nanoseconds, not milliseconds; values outside 0–999,999,999 are normalized into seconds if the result is in range
  • A date in January 1970 means a seconds value went into ofEpochMilli — the number is 1,000× too small. As millis, 1712345678 is only about 20 days past the epoch; the same digits as seconds are April 2024.
  • A date tens of thousands of years out for contemporary input means the reverse: a milliseconds value read as seconds.
  • For contemporary dates, 10 digits suggest seconds and 13 suggest milliseconds; the source unit, not digit count alone, determines the factory. The full table is on the timestamp to date page, and the bare unit conversion lives on milliseconds to seconds.
[SEC.04 // BACK TO A NUMBER]

Getting a number back out

GETEPOCHSECOND / TOEPOCHMILLI
  • instant.getEpochSecond() — whole seconds since the epoch. The exact pair of ofEpochSecond.
  • instant.toEpochMilli() — milliseconds in one call. Prefer it over hand-writing getEpochSecond() * 1000: the unit is in the name, and an overflow throws instead of silently wrapping.
  • instant.getNano() — sub-second nanos within the current second (0–999,999,999), not a count since 1970. Total nanoseconds is mathematically seconds × 1,000,000,000 + nanos, but that can overflow a long. For full Instant range use BigInteger.valueOf(instant.getEpochSecond()).multiply(BigInteger.valueOf(1_000_000_000L)).add(BigInteger.valueOf(instant.getNano())).
  • Elapsed time between two instants: Duration.between(a, b) or ChronoUnit.SECONDS.between(a, b) — clearer than subtracting epoch values by hand, and it keeps the unit in the type.
[SEC.05 // PARSING & PITFALLS]

Parsing, printing and the legacy bridge

ISO-8601 · ZONES · DATE
  • Instant.parse reads ISO-8601 instant text like 2024-04-05T19:34:38.901Z. An explicit offset such as +01:00 parses directly only on JDK 12+; on JDK 8–11 use OffsetDateTime.parse(text).toInstant() — same instant, works everywhere.
  • Printing needs a zone. A bare Instant has no local time to format: DateTimeFormatter date fields on it throw UnsupportedTemporalTypeException. Go through instant.atZone(ZoneId.of("Asia/Shanghai")) and format the ZonedDateTime.
  • ZoneId.of is strict. UTC, Asia/Shanghai, America/New_York are valid; GMT+8 is also valid and normalizes to GMT+08:00. China Standard Time is a Windows name, not a recognized JDK region ID; ambiguous short IDs such as CST need an explicit alias map or, preferably, an IANA region.
  • The legacy bridge: date.toInstant() and Date.from(instant) convert java.util.Date both ways, and java.sql.Timestamp has the same pair. Hold Instant in new code; convert only at the legacy boundary.
  • Testing: Instant.now(Clock) makes time injectable — freeze Clock.fixed(...) in tests instead of mocking statics.
[DOC.FAQ // INDEX]

ANSWERS

06 ITEMS
01 How do I get epoch seconds from a Java Instant?

Call instant.getEpochSecond() for seconds or instant.toEpochMilli() for milliseconds. Multiplying getEpochSecond() by 1,000 gives only the start of that second: it cannot recover the millisecond remainder. It can also overflow silently, whereas toEpochMilli() includes the remainder and throws on overflow.

02 Why does Instant.ofEpochMilli(1712345678) give a date in January 1970?

Unit mismatch: the number was meant as seconds, but ofEpochMilli reads it as milliseconds — 1,000× too small, about 20 days past the epoch. For contemporary dates those lengths are useful hints, but choose ofEpochSecond or ofEpochMilli from the declared unit.

03 What is the difference between Instant, OffsetDateTime and ZonedDateTime?

Instant is a plain count from 1970-01-01T00:00:00Z with no zone. OffsetDateTime adds one fixed offset such as +02:00. ZonedDateTime carries a full IANA ZoneId with historical and DST rules. All three represent the same moment: atZone/atOffset out, toInstant() back.

04 Does a Java Instant contain a timezone?

No. By contract an Instant is always UTC — that is what the trailing Z in its string form means. A zone enters only when you render it: instant.atZone(zone) produces a ZonedDateTime for display.

05 How do I convert java.util.Date to an Instant and back?

date.toInstant() goes one way, Date.from(instant) the other. A java.util.Date converts exactly to Instant at millisecond precision, but Date.from(instant) drops any sub-millisecond part and can fail for out-of-range values. java.sql.Timestamp has its own toInstant()/from pair that preserves nanoseconds within its supported range.

06 Can Instant.parse read a timestamp with a +01:00 offset?

On JDK 12 and newer, DateTimeFormatter.ISO_INSTANT accepts offsets, so Instant.parse works. On JDK 8–11 it throws; OffsetDateTime.parse(text).toInstant() returns the same instant on every JDK.

[SEC.MATRIX // RELATED]

Related tools

3 PAGES

Sources and specifications