Java Program to Convert String to Date

In this program, you’ll learn to convert string to date in Java using formatter.

Example 1: Convert String to Date using predefined formatters

  1. import java.time.LocalDate;
  2. import java.time.format.DateTimeFormatter;
  3. public class TimeString {
  4. public static void main(String[] args) {
  5. // Format y-M-d or yyyy-MM-d
  6. String string = "2017-07-25";
  7. LocalDate date = LocalDate.parse(string, DateTimeFormatter.ISO_DATE);
  8. System.out.println(date);
  9. }
  10. }

When you run the program, the output will be:

2017-07-25

In the above program, we’ve used the predefined formatter ISO_DATE that takes date string in the format 2017-07-25 or 2017-07-25+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);

Example 2: Convert String to Date using pattern formatters

  1. import java.time.LocalDate;
  2. import java.time.format.DateTimeFormatter;
  3. import java.util.Locale;
  4. public class TimeString {
  5. public static void main(String[] args) {
  6. String string = "July 25, 2017";
  7. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
  8. LocalDate date = LocalDate.parse(string, formatter);
  9. System.out.println(date);
  10. }
  11. }

When you run the program, the output will be:

2017-07-25

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.