Skip to content

Instantly share code, notes, and snippets.

@gauravkukade
Created May 14, 2021 18:30
Show Gist options
  • Save gauravkukade/b1ceabac137864efd7258b60610cd9dd to your computer and use it in GitHub Desktop.
Save gauravkukade/b1ceabac137864efd7258b60610cd9dd to your computer and use it in GitHub Desktop.
A Java Program to get current timestamp using using the java.time.Instant Check the blog at https://coderolls.com/how-to-get-current-timestamps-in-java/
import java.sql.Timestamp;
import java.time.Instant;
import java.util.Date;
/**
* A Java Program to get current timestamp using using the java.time.Instant
*
* @author Gaurav Kukade at coderolls.com
*
*/
public class InstantExample {
public static void main(String[] args) {
Instant instant = Instant.now();
System.out.println("1. instant: "+ instant); // 2021-05-13T15:05:18.734Z
//convert date object to instant
Date date = new Date();
Instant instantFromDate = date.toInstant();
System.out.println("2. instantFromDate: " +instantFromDate); // 2021-05-13T15:05:18.873Z
//get instnat from the java.sql.Timestamp
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
Instant instantFromTimestamp = timestamp.toInstant();
System.out.println("3. instantFromTimestamp: "+ instantFromTimestamp); // 2021-05-13T15:05:18.874Z
//get the epoch timestamp in milliseconds
//epoch timestamp is number of milliseconds since January 1, 1970, 00:00:00 GMT
Instant instant2 = Instant.now();
long timeStampMillis = instant2.toEpochMilli();
System.out.println("4. timeStampMillis: "+ timeStampMillis); // 1620918318874
//get the epoch timestamp in seconds
Instant instant3 = Instant.now();
long timeStampSeconds = instant3.getEpochSecond();
System.out.println("5. timeStampSeconds: "+ timeStampSeconds); // 1620918318
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment