To get the current timestamp in Java:
- Use the
Instant
class from Java 8 new date and time API. - The
Instant.now()
static method returns an object representing a specific moment in the timeline in UTC.
Instant now = Instant.now();
System.out.println(now);
// 2022-10-06T18:45:00.282494Z
An Instant
is a unique point in the timeline and is mainly used to represent timestamps in Java 8 and higher. You can use this class to get the current moment from the system clock.
Alternatively, you can also convert an instance of java.sql.Timestamp
to Instant
as shown below:
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
Instant now = timestamp.toInstant();
System.out.println(now);
// 2022-10-06T19:00:03.584Z
Another way to create an Instant
object is using the java.util.Date
class:
Date date = new Date();
Instant now = date.toInstant();
System.out.println(now);
// 2022-10-06T19:00:03.584Z
Note: To get a Unix timestamp (seconds from the epoch of
1970-01-01T00:00:00Z
) in Java, use theInstant.now().getEpochSecond()
method.
In Java 7 and below, you need to use the java.sql.Timestamp
class to get the current timestamp:
// Use System.currentTimeMillis()
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
// 2022-10-07 00:04:05.771
// Convert Date to Timestamp
Date date = new Date();
Timestamp timestamp = new Timestamp(date.getTime());
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.