Java – Get Current Timestamp

In Java, timestamps should be represented with java.time.Instant from Java 8, and java.sql.Timestamp till Java 7.

1) java.time.Instant [Java 8]

Get current instant using 3 methods.

public static void main(String[] args) throws ParseException 
{
	timeStampInJava8();
}

private static void timeStampInJava8() {
	//Method 1: Get current instant
	Instant instant = Instant.now();
	
	//Method 2: From java.sql.Timestamp
	Timestamp timestamp = new Timestamp(System.currentTimeMillis());
	Instant instant2 = timestamp.toInstant();
	
	//Method 3: From java.util.Date
	Date date = new Date();
	Instant instant3 = date.toInstant();
	
	System.out.println(instant);	//2018-07-14T08:10:44.270972700Z
	System.out.println(instant2);	//2018-07-14T08:14:37.943Z
	System.out.println(instant3);	//2018-07-14T08:14:37.943Z
}

2) java.sql.Timestamp [<= Java 7]

2 methods to get current timestamp.

public static void main(String[] args) throws ParseException 
{
	timeStampTillJava7();
}

private static void timeStampTillJava7() 
{
	//Method 1 - via System watch
	Timestamp timestamp1 = new Timestamp(System.currentTimeMillis());
	
	//Method2 - via java.util.Date
	Date date = new Date();
	Timestamp timestamp2 = new Timestamp(date.getTime());
	
	System.out.println(timestamp1);		//2018-07-14 13:48:39.336
	System.out.println(timestamp2);		//2018-07-14 13:48:39.336
}

Drop questions in comments section.

Happy Learning !!

References:

  1. java.sql.Timestamp
  2. java.time.Instant

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.