java convert string to date


In Java, you can use the SimpleDateFormat class to convert a string to a Date object. SimpleDateFormat is a class that can be used to parse and format dates according to a given format string.

Here’s an example of how you can use SimpleDateFormat to convert a string to a Date object:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
  public static void main(String[] args) throws ParseException {
    // Set up the SimpleDateFormat object
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // Parse the string using the parse method
    String dateString = "2022-07-03 15:23:01";
    Date date = sdf.parse(dateString);
    System.out.println(date);  // Outputs "Mon Jul 03 15:23:01 PDT 2022"

This code will parse the string “2022-07-03 15:23:01” using the format “yyyy-MM-dd HH:mm:ss”, and output the corresponding Date object.

Note that the parse method of SimpleDateFormat can throw a ParseException if the string is not in the expected format. You should make sure to handle this exception or declare it in your method signature.

You can also use the java.time package, introduced in Java 8, to parse dates and times. The java.time package includes the LocalDate and LocalDateTime classes, which can be used to represent a date and a date and time, respectively, without a time zone. You can use the parse method of these classes to parse a string into a LocalDate or LocalDateTime object.