In this post, we will see how to get current timestamp in java.
There are multiple ways to get current timestamp in java.
Table of Contents
Using Java 8’s Instant class
There are three ways to get timestamp using Java 8‘s java.time.Instant
class.
Using Instant.now()
1 2 3 4 |
// get current instant Instant instanceNow1 = Instant.now(); |
Using date.toInstant()
1 2 3 4 |
Date date=new Date(); Instant instanceNow2 = date.toInstant(); |
Using timestamp.toInstant()
1 2 3 4 |
Timestamp timestamp=new Timestamp(System.currentTimeMillis()); Instant instanceNow3 = timestamp.toInstant(); |
Here is complete example for get current timestamp in java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package org.arpit.java2blog; import java.util.Date; import java.sql.Timestamp; import java.time.Instant; public class InstantExampleMain { public static void main(String[] args) { // get current instant Instant instanceNow1 = Instant.now(); System.out.println(instanceNow1); // from java.util.Date to instant Date date=new Date(); Instant instanceNow2 = date.toInstant(); System.out.println(instanceNow2); // from java.sql.Timestamp to instant Timestamp timestamp=new Timestamp(System.currentTimeMillis()); Instant instanceNow3 = timestamp.toInstant(); System.out.println(instanceNow3); } } |
Output:
2020-03-23T17:41:21.541Z
2020-03-23T17:41:21.726Z
2020-03-23T17:41:21.727Z
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package org.arpit.java2blog; import java.sql.Timestamp; import java.util.Date; public class TimestampMain { public static void main(String[] args) { // get current timestamp with System.currentTimeMillis() Timestamp timestampNow = new Timestamp(System.currentTimeMillis()); System.out.println(timestampNow); // get current timestamp with date Date date=new Date(); Timestamp timestampDate = new Timestamp(date.getTime()); System.out.println(timestampDate); } } |
Output:
2020-03-23 23:15:07.88
2020-03-23 23:15:07.895
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?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.