How to convert Java strings to timestamps?

There are several common methods in Java for converting strings to timestamps.

  1. Using the SimpleDateFormat class:
String dateString = "2021-01-01 12:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse(dateString);
long timestamp = date.getTime();
  1. Utilize the DateTimeFormatter class (Java 8 or higher)
String dateString = "2021-01-01 12:00:00";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.parse(dateString, dtf);
long timestamp = localDateTime.toInstant(ZoneOffset.UTC).toEpochMilli();
  1. Utilize the java.sql.Timestamp class:
String dateString = "2021-01-01 12:00:00";
Timestamp timestamp = Timestamp.valueOf(dateString);
long timestampInMilliseconds = timestamp.getTime();

In each of these methods, you first need to parse the strings into Date objects or LocalDateTime objects according to specific date formats before converting them into timestamps.

bannerAds