In this quick article, you will learn how to get current timestamp in Java.
Using Instant
Class
In Java 8 and higher, timestamps are represented using java.time.Instant
class from Java 8 new date and time API. An Instant
represents a specific moment on the timeline in UTC.
To get the current Instant
object from the system clock, you can do the following:
Instant now = Instant.now();
// 2019-12-23T09:06:32.071Z
Instant.now()
returns the current moment on the timeline since the first second of January 1, 1970 UTC/Greenwich (1970-01-01 00:00:00).
Alternatively, you can also convert an instance of java.sql.Timestamp
to Instant
(not recommended) as shown below:
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
Instant now = timestamp.toInstant();
Another way to create an Instant
is by using the java.util.Date
class:
Date date = new Date();
Instant now = date.toInstant();
Check out How to get the current date and time in Java guide for more new date and time API examples.
Using Timestamp
Class
In Java 7 and below, you can use the java.sql.Timestamp
class to get current timestamps:
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
// 2019-12-23 14:21:51.068
Alternatively, you can also convert an instance of Date
to a Timestamp
object:
Date date = new Date();
Timestamp timestamp = new Timestamp(date.getTime());
Further Reading
You may be interested in reading the following Java date and time tutorials:
- Introduction to Java 8 Date and Time API
- How to get current date and time in Java
- How to convert a string to date in Java
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.