Google News
logo
Java Program to Convert String to Date
In the following example of Java Program to Convert String to Date in Java using formatter :

* Convert String to Date using predefined formatters

* Convert String to Date using pattern formatters

Convert String to Date using predefined formatters :

Program :
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class TimeString {

    public static void main(String[] args) {
        // Format y-M-d or yyyy-MM-d
        String string = "2018-05-16";
        LocalDate date = LocalDate.parse(string, DateTimeFormatter.ISO_DATE);

        System.out.println(date);
    }
}
Output :
2018-05-16
In the above program, we've used the predefined formatter ISO_DATE that takes date string in the format 2018-05-16 or 2018-05-16+05:45'.

The LocalDate's parse() function parses the given string using the given formatter. You can also remove the ISO_DATE formatter in the above example and replace the parse() method with:
LocalDate date = LocalDate.parse(string, DateTimeFormatter);​



Convert String to Date using pattern formatters :

Program :
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class TimeString {

    public static void main(String[] args) {
        String string = "May 16, 2018";

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
        LocalDate date = LocalDate.parse(string, formatter);

        System.out.println(date);
    }
}
Output :
2018-05-16
In the above program, our date is in the format MMMM d, yyyy. So, we create a formatter of the given pattern.

Now, we can parse the date using LocalDate.parse() function and get the LocalDate object.