Fragmentos de timestamp Unix en Java

Ejemplos de Java para segundos epoch actuales, milisegundos, conversión con Instant, formateo con zona horaria y las APIs modernas de java.time.

Java timestamp basics

Modern Java code should prefer java.time.Instant for timestamp work. Instant.now().getEpochSecond() gives Unix seconds and Instant.now().toEpochMilli() gives Unix milliseconds.

Timezone-aware Java formatting

Convert an Instant to a ZonedDateTime with ZoneId when displaying local time. Keep storage and comparisons in Instant or UTC, then format only at the edge of the application.

Java production notes

The java.time API separates instants, local calendar values, and timezone-aware display. Use Instant for the moment that should be stored or compared. Use ZonedDateTime only after selecting a ZoneId for a user, tenant, or report. Avoid legacy Date and Calendar unless an older library requires them.

  • Use Instant.now().getEpochSecond() for Unix seconds
  • Use Instant.now().toEpochMilli() or System.currentTimeMillis() for milliseconds
  • Use Instant.ofEpochSecond(seconds) when receiving standard Unix timestamps
  • Use DateTimeFormatter.ISO_INSTANT for compact UTC API output

Frequently checked Java details

Should new code use Date or Instant?
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.
What is the difference between Instant and ZonedDateTime?
Instant is the exact moment in UTC. ZonedDateTime is that moment displayed with a ZoneId, which is useful for user-facing dates and reports.
How do I verify Java epoch values?
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.