Convert LocalDateTime to Timestamp in Java

Convert LocalDateTime to Timestamp in java

In this post, we will how to convert LocalDateTime to Timestamp .

Before learning how to convert localdatetime to timestamp, let us learn about LocalDateTime and Timestamp, and understand the importance of this conversion.

LocalDateTime

LocalDateTime was introcuded in Java 8. LocalDateTime can be imported time package: import java.time.LocalDateTime;

LocalDateTime is an immutable object used to represent date in the format
Year-date-month-day-hour-minute-second. Time is represented in nanosecond precision.
Example :

Output :

2020-11-07T10:16:02.234214500

Note : Above output is in accordance to the time when I compiled my code. And output is subject to change, as the time and date changes.
LocalDateTime.now() : Returns LocalDateTime object at that particular instant of time.

Timestamp

Timestamp class can be imported from java.sql package, i.e., import java.sql.Timestamp;
This class allows JDBC API to identify as SQL Timestamp. SQL timestamp has fractional seconds value, This class objects makes timestamp compatible to SQL timestamp, making it easy for the JDBC API to run queries on time and manipulate database.

Timestamp provides methods to format and parse operations to support JDBC.

Convert LocalDateTime to Timestamp

You can use Timestamp’s valueOf() method to convert LocalDateTime to Timestamp. Converting LocalDateTime to Timestamp helps us to convert time into Timestamp that is compatible with SQL timestamp datatype.

Timestamp.valueof(LocalDateTime local): Returns Timestamp object with same date, same time, in correspondence to the time provided in LocalDateTime object.

Output :

Local Date Time : 2020-11-18T23:49:33.175092900
Time stamp : 2020-11-18 23:49:33.1750929

As mentioned above, output can subject to change based on the time code compiled.

That’s all about how to convert LocalDateTime to Timestamp in Java

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *