These Java examples use Unix seconds for the portable baseline and show milliseconds only where the runtime exposes them naturally. The question to answer before copying a snippet is simple: what unit does the next API expect?
Get the current Unix time
long seconds = Instant.now().getEpochSecond();
long milliseconds = Instant.now().toEpochMilli();
Convert a timestamp to UTC
Instant instant = Instant.ofEpochSecond(1700000000);
String iso = instant.toString();
Production note
Use Instant for storage and transport. Convert it to a ZonedDateTime only when a named region is needed for display or calendar logic.
Keep the unit in the field name when a value crosses a boundary: createdAtSeconds and createdAtMs are longer than createdAt, but much less mysterious during an incident.
Frequent questions:
- Q: Should new code use Date or Instant?
- A: Use Instant for timestamp storage and comparisons. Legacy Date may still appear in old libraries, but java.time is clearer for seconds, milliseconds, and timezone-aware formatting.
- Q: What is the difference between Instant and ZonedDateTime?
- A: Instant is the exact moment in UTC. ZonedDateTime is that moment displayed with a ZoneId, which is useful for user-facing dates and reports.
- Q: How do I verify Java epoch values?
- A: Print Instant.ofEpochSecond(seconds) or Instant.ofEpochMilli(milliseconds) before saving a value. The ISO output should match the UTC instant expected by the receiving system.
- Q: How do I convert millis to a Unix timestamp in Java?
- A: Divide System.currentTimeMillis() by 1000L for a long of Unix seconds: long secs = System.currentTimeMillis() / 1000L. Use Instant.ofEpochSecond(secs) to round-trip back into an Instant.
- Q: How do I convert currentTimeMillis to a date in Java?
- A: Wrap it in an Instant: Instant.ofEpochMilli(System.currentTimeMillis()). For display, combine with a ZoneId: ZonedDateTime.ofInstant(instant, ZoneId.of("UTC")) or any other IANA zone.