Javatpoint Logo
Javatpoint Logo

How to Convert String to Timestamp in Java?

In Java, converting a string to a timestamp involves parsing the string representation of a date and time into a java.sql.Timestamp object. The process is commonly required when dealing with date and time data obtained from external sources or user inputs. In this section, we will explore how to convert a string to a timestamp in Java, covering different scenarios and methods.

Method 1: Using SimpleDateFormat

One of the traditional ways to convert a string to a timestamp is by using the SimpleDateFormat class. This class allows you to define a pattern that represents the format of the date and time in the input string. Here's an example:

File Name: StringToTimestampExample.java

Output:

Input String: 2024-01-04 12:30:45
Converted Timestamp: 2024-01-04 12:30:45.0

In this example, we define the pattern "yyyy-MM-dd HH:mm:ss" to match the format of the input string. The SimpleDateFormat is then used to parse the string into a Date object, and we create a Timestamp object from that Date.

Method 2: Using Instant and DateTimeFormatter (Java 8 and later)

With the introduction of the java.time package in Java 8, a more modern and flexible approach is available using Instant and DateTimeFormatter classes. Here's an example:

File Name: StringToTimestampExample2.java

Output:

Input String: 2024-01-04 12:30:45
Converted Timestamp: 2024-01-04 12:30:45.0

In this example, we use DateTimeFormatter to define the pattern, and Instant to represent a point in time. The input string is parsed into an Instant object, and then we convert it to a Timestamp.

Conclusion

Converting a string to a timestamp in Java involves parsing the string using a specific date and time pattern. The choice between SimpleDateFormat and the newer DateTimeFormatter depends on the Java version you are using. With Java 8 and later, it's recommended to use the java.time API for better functionality and thread-safety. Always handle exceptions that may occur during parsing to ensure robustness in your code.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA