Java LocalDateTime to Timestamp Conversion
LocalDateTime to Timestamp Conversion can be done using Timestamp.valueOf() method provided by Timestamp class. In the recent tutorial, we have seen how to Convert Java Timestamp to LocalDateTime Conversion.
In this tutorial, we will cover in deep about valueOf() method of the Timestamp class and how we can convert LocalDateTime to Timestamp.
Java LocalDateTime to Timestamp Conversion
public static Timestamp valueOf(LocalDateTime dateTime)
This method returns an instance of Timestamp from a LocalDateTime instance using the same year, month, day of month, hours, minutes, seconds and nanoseconds dateTime value as the provided LocalDateTime instance.
Parameters:
dateTime - a LocalDateTime instance to convert.
Returns:
a Timestamp instance converted from LocalDateTime.
Throws:
NullPointerException is thrown if dateTime instance is null.
Since:
This method is since Java version 1.8.
Example:
import java.sql.Timestamp;
import java.time.LocalDateTime;
public class LocalDateTimeToTimestamp1 {
public static void main(String[] args) {
// Creating LocalDateTime instance
LocalDateTime currentDateTime = LocalDateTime.now();
// Printing LocalDateTime currentDateTime
System.out.println("LocalDateTime currentTime : " + currentDateTime);
// LocalDateTime currentTime : 2020-07-04T21:16:39.488
// Converting Java LocalDateTime to Timestamp
Timestamp timestamp = Timestamp.valueOf(currentDateTime);
// Printing Converted Value Timestamp
System.out.println("Timestamp : " + timestamp);
// Timestamp : 2020-07-04 21:16:39.488
}
}
Output:
Timestamp: 2020-07-04 21:20:56.465
LocalDateTime: 2020-07-04T21:20:56.465
Conclusion:
In this tutorial, we have covered how to Convert Java LocalDateTime to Timestamp instance using Timestamp.valueOf() method.
Happy Learning!!!
Comments
Post a Comment
If you have any doubts, Please let me know.