Core Java

Timestamp Java Example

In this article we will create a Timestamp Java Example and Timestamp sql.

1. Introduction

In a typical application, there are a lot of events like orders receipt, payment request sent, users logging in, orders shipping to name a few. The events may also be negative such as network failure, invalid user login, product failure so on.

To answer questions around such events like “When did you receive your order?”, “How long did you take to process an order?”, “When was the ordered product shipped?”, “When there was a network failure?”, the timestamps are helpful to a great extent. As the word suggests timestamp is the stamp of a time when the event occurred.

In Java, usually, we record a timestamp based on Java epoch. Java epoch as per Javadoc is a long number representing the exact seconds elapsed from the standard Java epoch of 1970-01-01T00:00:00Z (January 1st, 1970 00:00 GMT).

In this article we give examples about two timestamp classes in Java including their constructors and methods and the classes discussed are java.sql.Timestamp and java.time.Instant.

2. Timestamp classes in Java

2.1 java.sql.Timestamp

As per Javadoc, Timestamp is a wrapper around Java Date which allows JDBC API to recognize this as an SQL TIMESTAMP. Additionally, this allows for nanoseconds to be represented as a fraction of a second.

Functionally, this used to time the database events such as creation of new records and update, removal of existing records, etc., Further, it is also used to compare two database events based on timestamp, say did the database event A occur after/before the database event B.

The following example creates two Timestamp objects and compares the two objects:

Example 1

public void funWithJavaSQLTimestamp() {
		System.out.println("\nTimestamps");
		System.out.println("==========");
		
		// Create start date timestamp object
		Timestamp startTimestamp = new Timestamp(System.currentTimeMillis());
		
		// Print current timestamp
		System.out.println("Start Timestamp is : " + startTimestamp.toString());		
		
		// Introduce some delay
		System.out.println("Introducing some random delay!");
		
		int randomNumber = new Random().nextInt(10);
		try {
			Thread.sleep(randomNumber * 1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// Create end date time stamp
		Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
		System.out.println("End Date is : " + endTimeStamp.toString());
		
		System.out.println("\nTimestamp Comparisons");
		System.out.println("=====================");
		// Check start date is after/before start date 
		System.out.println("Is Start Date after the End Date? " 
		                          + (startTimestamp.after(endTimeStamp)? "Yes" : "No"));
		System.out.println("Is Start Date before the End Date? " 
		                          + (startTimestamp.before(endTimeStamp)? "Yes" : "No"));
		
		// Alternative method of comparing timestamps
		int comparison = startTimestamp.compareTo(endTimeStamp);
		System.out.println("The comparison between startDate and endDate: " + comparison);
		System.out.println("\tHere 0 means equal\n\t-1 means start date is less than "
				           + "end date\n\t+1 means start date is greater than end date.");				
	}

This following shows how to set Timestamp in a PreparedStatement object while creating a new database record. The example assumes the database table structure as shown in the picture:

Timestamp Java - Table Structure for example 2
Table Structure for example 2

Example 2

public PreparedStatement generatePreparedStatement(Connection con, long id, 
			         String productName, int quantity, double rate) throws SQLException {
		
		String query = "INSERT INTO PRODUCT_ORDER "
				+ "(ID, PRODUCT_NAME, QUANTITY, RATE, CREATED_TIME) "
				+ "                                      VALUES (?, ?, ?, ?, ?)";
		
		PreparedStatement statement = con.prepareStatement(query);
		statement.setLong(1,  id);
		statement.setString(2,  productName);
		statement.setInt(3, quantity);
		statement.setDouble(4, rate);
		
		
		// Example to show how to set timestamp 
		// while creating a new record
		Timestamp ts = new Timestamp(System.currentTimeMillis());
		statement.setTimestamp(5, ts);	
		
		return statement;		
	}

2.2 java.time.Instant

Instant class, as per Javadocs, is also used to record the timestamps for the events in the application.

Unlike Timestamp this is not specially designed for SQL queries. This is for general usage. Similar to Timestamp, Instant also provides methods for comparison like isAfter and isBefore. Check javadocs for more information.

Along with the comparison methods, it also provides time calculation methods to add/subtract time in seconds, time in millis, and time in nanos.

The example for the Instant class follows:

public void funWithInstant() {
		
		// Creating the timestamps using Instant
		System.out.println("\nInstants");
		System.out.println("=========");
		Instant startInstant = Instant.now();
		System.out.println("Start Instant time : " + startInstant);
	
	
		Instant endInstant = Instant.now();		
		System.out.println("End Instant time : " + endInstant);
		
		// Instant comparisons
		System.out.println("\nInstant Comparisons");
		System.out.println("===================");
		// Check start date is after/before start date 
		System.out.println("Is Start Date after End Date? " 
		                          + (startInstant.isAfter(endInstant)? "Yes" : "No"));
		
		System.out.println("Is Start Date before End Date? " 
		                          + (startInstant.isBefore(endInstant)? "Yes" : "No"));
		
		// Instant calculations
		System.out.println("\nInstant Calculations");
		System.out.println("====================");
		
		System.out.println("Adding 2 seconds  to the start instant. "
				+ "Result is : " + startInstant.plusSeconds(3));
		System.out.println("Adding 200 millis to the start instant. "
				+ "Result is : " + startInstant.plusMillis(200));
		System.out.println("Adding 500 nanos  to the start instant. "
				+ "Result is : " + startInstant.plusNanos(500));		
	}

3. Execution

In this section we will execute the programs and see how it is working.

Prerequisites:

  • Java 1.8 installed in the system. Environment variables JAVA_HOME set to the Java location and PATH set to the directory containing javac and java binaries ( %JAVA_HOME%/bin on windows or $JAVA_HOME/bin on Linux machines)
  • Source code zip and downloaded to a location (say, C:\JavaCodeGeeks. This would be different for Linux)
  • Eclipse IDE (Photon Release (4.8.0) is used for this example)

3.1 Execution using eclipse

Step 1: Open the Eclipse IDE.
Step 2: Click On File >> Import.
Step 3: From the “Import” menu select “Existing Projects into Workspace”.

Timestamp Java
Import the TimestampeExample project

Step 4: Click Next.
Step 5: On the next page, click browse and select the root of the example folder (say,C:\JavaCodeGeeks). Click on the “Finish” button.

Timestamp Java - Choose Timestamp project
Choose Timestamp project

Step 6: Ensure Package Explorer is loaded and lists all the files as shown in the figure below.
Step 7: Click on src >> com.javacodegeeks.examples >> TimestampExample
Step 8: Right-click on TimestampExample.java, from the menu, choose
“Run As” >> “Java Application”

Run as Java Application
Run as Java Application

See the sample output as below:

Timestamps
==========
Start Timestamp is : 2020-05-17 10:59:29.465
Introducing some random delay!
End Date is : 2020-05-17 10:59:32.485

Timestamp Comparisons
=====================
Is Start Date after the End Date? No
Is Start Date before the End Date? Yes
The comparison between startDate and endDate: -1
	Here 0 means equal
	-1 means start date is less than end date
	+1 means start date is greater than end date.

Instants
=========
Start Instant time : 2020-05-17T09:59:32.487Z
End Instant time : 2020-05-17T09:59:32.568Z

Instant Comparisons
===================
Is Start Date after End Date? No
Is Start Date before End Date? Yes

Instant Calculations
====================
Adding 2 seconds  to the start instant. Result is : 2020-05-17T09:59:35.487Z
Adding 200 millis to the start instant. Result is : 2020-05-17T09:59:32.687Z
Adding 500 nanos  to the start instant. Result is : 2020-05-17T09:59:32.487000500Z

4. Download the Eclipse Project

That is a tutorial about the timestamps in Java.

Download
You can download the full source code of this example here: Timestamp Java Example

Shivakumar Ramannavar

Shivakumar has 16+ years of experience in Java Development, Cloud and also has a lot of passion in Cloud-native Applications and Kubernetes. Shiva has a Bachelor's Degree from Visweswaraiah Technological University, India. Shiva has been involved in the development of IT systems using Java/J2EE, Kubernetes, and has designed tonnes of applications both on-premise and on-cloud. Shiva strongly believes there is a great revolution of cloud-native technologies and that we can create a world of difference through learning, sharing, and caring among the community.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Suma
Suma
4 years ago

Nice

Back to top button