-->
Skip to main content

Convert Java LocalDate to Timestamp [2021]

Convert Java LocalDate to Timestamp [2021]

To Convert Java LocalDate to Timestamp we have one way
  1. Using Timestamp.ValueOf(LocalDateTime time) to convert first LocalDate to LocalDateTime and then using LocalDateTime in method ValueOf to convert to Timestamp.
we come across these cases usually where we need to convert timestamp to localdatetimestamp to localdatetimelocaldatetime to timestamplocaldate to localdatetimelocaldatetime to date, localdate to instant, etc. In this tutorial, we are covering a similar case to convert java localdate to timestamp using Timestamp.valueOf(LocalDateTime time) method.

Java LocalDate to Timestamp

Java LocalDate to Timestamp

1. public static Timestamp valueOf(LocalDateTime dateTime)

This method returns an instance of java.sql.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.LocalDate;
 import java.time.LocalTime;

 public class LocalDateToTimestampEx1 {
   public static void main(String[] args) {
	LocalDate now = LocalDate.now();
	//Creating localdatetime with startofday
	Timestamp timestamp = Timestamp.valueOf(now.atStartOfDay());
	System.out.println("LocalDate to Timestamp : " + timestamp);
		
	//Creating localdatetime with localtime
	Timestamp timestamp1 = Timestamp.valueOf(now.atTime(LocalTime.now()));
	System.out.println("LocalDate to Timestamp : " + timestamp1);
    }
 }

Output:

LocalDate to Timestamp : 2020-07-11 00:00:00.0
LocalDate to Timestamp : 2020-07-11 22:51:20.302

Conclusion:

In this tutorial, we have covered how to Convert Java LocalDate to Timestamp instance using Timestamp.valueOf(LocalDateTime time) method.

Thanks for reading this tutorial so far. If you like this tutorial then please share it with your friends and colleagues. If you have any questions, doubts, suggestions, or feedback then please drop a comment and I'll try to answer your question.

Happy Learning!!!

Comments