Get current timestamp in java

In this post, we will see how to get current timestamp in java.

There are multiple ways to get current timestamp in java.

Using Java 8’s Instant class

There are three ways to get timestamp using Java 8‘s java.time.Instant class.

Using Instant.now()

Using date.toInstant()

Using timestamp.toInstant()

Here is complete example for get current timestamp in java.

Output:

2020-03-23T17:41:21.541Z
2020-03-23T17:41:21.726Z
2020-03-23T17:41:21.727Z

Using java.sql.Timestamp

You can also java.sql.Timestamp to get current Timestamp.

Output:

2020-03-23 23:15:07.88
2020-03-23 23:15:07.895

Conclusion

You should use java.time.Instant to get current timestamp in case you are using Java 8 or greater version. If you are using Java 7 or below, then only you should use java.sql.Timestamp to get current timestamp in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *