How to convert String Date to Timestamp in Java?

In this tutorial I will teach you example program for converting String Date to Timestamp in Java. You will be able to convert String representation of date into Timestamp.

String Date to Timestamp example in Java

Java is programming language with huge set of API for working with the Date in your program. You will use these API for converting, creating, updating date object in Java program.

In this example program we are going to convert String representation of Date object to Timestamp. The java.sql.Timestamp is the wrapper around java.utilDate class is used by the JDBC API to identify SQL TIMESTAMP. This class add the functionality to hold fractional seconds in date to a precision of nanoseconds.

This class is useful while working with the JDBC.

1) We have a variable with String representation of date:

String dt = "10-Jan-2017";

2) Define the pattern of the date to be parsed. In our case its:

String pattern = "dd-MMM-yyyy";

3) Create object of SimpleDateFormat class with above patters as shown below:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

4) Convert String date to java.utilDate using following code:

date = simpleDateFormat.parse(dt);

5) Finally covert date object to Timestamp with following code:

java.sql.Timestamp timestamp = 
  new java.sql.Timestamp(date.getTime());

Here is the full code of the program to convert Date String format to Timestamp:

package net.roseindia;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

 * Web:
 * Example of Converting String date
 * into timestamp from a Java program

public class StringDateToTimestamp {

public static void main(String[] args) {
	String dt = "10-Jan-2017";
	String pattern = "dd-MMM-yyyy";
	SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
	Date date = null;
	try {
		date = simpleDateFormat.parse(dt);
	} catch (ParseException e) {
	System.out.println("Date:" + date);
	java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
	System.out.println("Timestamp:" + timestamp.toInstant().toString());


After running the program it will give following output:

Date:Tue Jan 10 00:00:00 IST 2017

In this tutorial we have explained Java code for converting String Date into Timestamp. Here are few more related tutorials related to the Date conversion in Java:

  1. Convert Date To Calendar
  2. Convert Date to Timestamp
  3. Convert String to Date
  4. Convert Date to String
  5. Calendar Example
  6. Convert Date to Milliseconds