What’s the best way to get current timestamp in Java

When I search online, I see a lot of different ways to get timestamp in Java like java.util.Date or java.sql.Timestamp. My project has nothing to do with SQL so I don’t think I should be using the Timestamp class from the java.sql package.

What’s the recommended way to get timestamps in Java?

  1. Accepted Answer

Accepted Answer

Use modern classes in the java.time package (Java 8 Date-Time API) for all your date and time needs. Avoid legacy Date/Time classes

Prior to Java 8, working with Date-Time in Java was messy and the supporting APIs had many shortcomings. These libraries are still available but I’d refer to these as legacy libraries. Their shortcomings included Thread-safety issue, implicitly applying the current JVM’s timezone resulting in different answers on different machines, poor and inconsistent API design, etc.

The “legacy” libraries include:

  • java.util.Date
  • java.sql.Date
  • java.sql.TimeStamp
  • java.sql.Time
  • java.util.GregorianCalendar

Avoid the use of these classes. Instead, use the modern Date-Time API that was introduced with Java 8 and can be found in the java.time package.

The “modern” libraries include:

  • java.time.Instant: Get a Moment in UTC
  • java.time.OffsetDateTime: Moment with UTC offset
  • java.time.ZonedDateTime: Moment with timezone for country or region
  • java.time.LocalDateTime: Date and time without a timezone e.g. 2007-12-03T10:15:30. E.g. birthdays. Cannot represent an instant without additional information such as time-zone.
  • java.time.LocalDate and java.time.LocalTime: Same as above but for Date and Time only, respectively.
  • java.time.OffsetTime: A time with an offset from UTC/Greenwich, such as 10:15:30+01:00. This is impractical for many real-world use cases.

Now that I have explained the difference between legacy and modern Date Time classes in Java, let’s look at a few examples of how to get current timestamp (UTC) in Java (8 or later versions):

ZonedDateTime zdt = ZonedDateTime.now(ZoneOffset.UTC);

This outputs on my machine: 2022-08-14T17:01:03.653702644Z

You can also use ` Instant.now()` to get the current timestamp:


Speak Your Mind