How to convert String to Timestamp in Java?

To convert String to Timestamp in Java, use SimpleDateFormat.parse, then create a Timestamp out of Date.getTime.

Here's how you do it:

String string = "2021-12-15 12:34:56.789";

try {
  var date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS").parse(string);
  java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());

  System.out.println(timestamp); // 2021-12-15 00:34:56.789
} catch (ParseException exception) {
  exception.printStackTrace();
}