• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us

How to Convert a String to a Timestamp Java

April 30, 2024 //  by Anees Asghar

A timestamp is a date-time object in Java that is used to represent date-time information with precision. Java users often go through a situation where they need to convert a string representation of a date into a timestamp object.

In this tutorial, we’ll use different built-in Java classes to convert a string date to a timestamp. 

How to Convert a String to a Timestamp in Java

To convert a date string into a timestamp in Java, we can use built-in methods like “SimpleDateFormat.parse()” and “Timestamp.valueOf()”. 

1. Converting a String to a Timestamp Using SimpleDateFormat.parse()

The SimpleDateFormat class provides a method named parse() that takes a string and parses it into a date. This method can parse a string(date) into a timestamp. For instance, in the following code snippet, we invoke the parse() method on the given date string to parse into a timestamp according to a specific date format:

import java.sql.Timestamp;
import java.text.*;

public class ExampleClass {
  public static void main(String[] args) {
String givenDate = "2020/11/14 10:11:12";
SimpleDateFormat formatDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try {
java.util.Date parseDate = formatDate.parse(givenDate);
Timestamp convertedTimestamp = new Timestamp(parseDate.getTime());
System.out.println("The Given Date String is ==> " + givenDate);
System.out.println("The Data Type of Given Date is ==> " + givenDate.getClass().getName());
System.out.println("The Converted Timestamp is ==> " + convertedTimestamp);
System.out.println("The Data Type of the Converted Timestamp is ==> " + convertedTimestamp.getClass().getName());
} catch (ParseException excep) {
excep.printStackTrace();
}
}
}

Code Explanation 

  • First, we import the required classes from the “sql” and “text” packages.
  • After this, we initialize a date string to a variable “givenDate”. 
  • Next, we use the SimpleDateFormat() constructor to specify a valid date format (according to which the provided date will be parsed). 
  • In the next line, we invoke the parse() method on the given string to convert it into a date.
  • Up next, we use the Timestamp() constructor to convert the parsed date into a timestamp.
  • Finally, we print the given string and the converted timestamp on the console. Also, we printed the data type of the given date string and the converted timestamp to make things clear:

The output confirms the conversion of the given string into a timestamp using the parse() method. 

2. Converting a String to a Timestamp Using Timestamp.valueOf()

The valueOf() is an easy-to-use built-in method of the Timestamp class. This method can be used to convert a date string to a timestamp, as shown in the following code snippet:

import java.sql.Timestamp;public class ExampleClass {
  public static void main(String[] args) {
  String givenDate = "2021-04-11 01:12:12";
  try {
Timestamp convertedDate = Timestamp.valueOf(givenDate);
System.out.println("The Given Date String is ==> " + givenDate);
System.out.println("The Data Type of Given Date is ==> " + givenDate.getClass().getName());
System.out.println("The Converted Timestamp is ==> " + convertedDate);
System.out.println("The Data Type of the Converted Timestamp is ==> " + convertedDate.getClass().getName());
} catch (Exception excep) {
excep.printStackTrace();
}
  }
}

In the above code snippet, 

  • At the program’s start, we import the Timestamp class from the “java.sql” package.
  • In the main() method, we create a string-type variable and assign it a date value.
  • Up next, we invoke the valueOf() method on the given date string to convert it into a timestamp.
  • Finally, we print the given date and the converted timestamp (along with their corresponding data types) on the console:

The output confirms that the valueOf() method successfully converted the given string to a timestamp.

How to Format/Convert a Timestamp to a String in Java?

The “Timestamp” class of the “java.sql” package offers a “toString()” method that retrieves a string representation of the timestamp in JDBC timestamp escape format. This method lets us convert a timestamp object into a string in Java:

import java.sql.Timestamp;
public class ExampleClass {
  public static void main(String[] args) {
    try {
Timestamp givenTimestamp = Timestamp.valueOf("2021-04-11 01:12:12");
System.out.println("The Given Timestamp is ==> " + givenTimestamp);
System.out.println("The Data Type of Given Timestamp is ==> " + givenTimestamp.getClass().getName());

String convertedTimestamp = givenTimestamp.toString();
System.out.println("The Converted Timestamp is ==> " + convertedTimestamp);
System.out.println("The Data Type of the Converted Timestamp is ==> " + convertedTimestamp.getClass().getName());
} catch (Exception excep) {
excep.printStackTrace();
}
  }
}

In this example,

  • We declare a timestamp using the valueOf() method and initialize it to a variable named “givenTimestamp”.
  • Also, we print the initialized timestamp and its data type on the console.
  • After this, we use the toString() method on the given timestamp to convert it into a string.
  • For verification purposes, we print the converted timestamp along with its data type on the console, as shown in the following screenshot: 

That’s all from converting a string to a timestamp in Java.

Conclusion

To convert a string to a timestamp in Java, use the “parse()” or the “valueOf()” methods of the SimpleDateFormat and Timestamp classes, respectively. On the other hand, if you need to format/convert a timestamp object to a String, you can use the toString() method of the Timestamp class. In this tutorial, all these methods are explained with appropriate examples.

Category: Java

About Anees Asghar

Anees, a go-to expert of various technologies like PostgreSQL, Java, JS, and Linux. He has been contributing to the community through his words. A passion for serving the people excites him to craft primo content.

Previous Post: « How to Write Data to a CSV File in Java
Next Post: How to Get a Timezone List in Java »

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

How to Initialize an Array in Java

Introduction to Java Server Faces (JSF)

Introduction to Java 6.0 New Features, Part–1

Java 6.0 Features Part – 2 : Pluggable Annotation Processing API

Introduction to Java Server Faces(JSF) HTML Tags

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact