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.
[toc]

Using Java 8’s Instant class

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

Using Instant.now()

// get current instant  
Instant instanceNow1 =  Instant.now();

Using date.toInstant()

Date date=new Date();
Instant instanceNow2 = date.toInstant();

Using timestamp.toInstant()

Timestamp timestamp=new Timestamp(System.currentTimeMillis());
Instant instanceNow3 = timestamp.toInstant();

Here is complete example for get current timestamp in java.

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

Using java.sql.Timestamp

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

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

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.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.