In this post, we will how to convert LocalDateTime to Timestamp .
Table of Contents
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 :
1 2 3 4 |
LocalDateTime current_date_time = LocalDateTime.now(); //returns time and date object of today's date. System.out.println(current_date_time); //printing the time and date |
Output :
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package org.arpit.java2blog; import java.sql.Timestamp; import java.time.LocalDateTime; public class ConvertLocalDataTimeToTimestamp { public static void main(String[] args) { LocalDateTime current_date_time = LocalDateTime.now(); //returns time and date object of today's date. //printing the time and date System.out.println("Local Date Time : " + current_date_time); //Timestamp object Timestamp timestamp_object = Timestamp.valueOf(current_date_time); System.out.println("Time stamp : " + timestamp_object); } } |
Output :
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