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.sql.Timestamp. My project has nothing to do with SQL so I don’t think I should be using the
Timestamp class from the
What’s the recommended way to get timestamps in Java?
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:
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
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.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); System.out.println(zdt);
This outputs on my machine:
You can also use ` Instant.now()` to get the current timestamp:
System.out.println( Instant.now().toString() );