How to convert a string to a date in Java?

In Java, the SimpleDateFormat class can be used to convert a String to a Date. Here is an example code:

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

public class StringToDateExample {
    public static void main(String[] args) {
        String dateString = "2021-01-01";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        
        try {
            Date date = sdf.parse(dateString);
            System.out.println(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In the example above, we first create a SimpleDateFormat object and specify the date format as “yyyy-MM-dd”. Then we use the parse method to convert the string to a Date object. If the conversion is successful, the converted Date object will be printed out. If the conversion fails, the exception information will be printed out.

bannerAds