Java Program to Convert String to Date

In this java program, we will learn about how to convert string to date in Java using parse() method of DateFormat and DateTimeFormatter classes.

Java Program to Convert String to Date using Predefined DateTimeFormatter

The LocalDate class provides parse() methods for parsing a String that contains date and time information. To convert String objects to LocalDate, the String must represent a valid date or time according to ISO_DATE or ISO_LOCAL_DATE_TIME format.

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

public class DateTimeString {
  public static void main(String[] args) {
    // Date string in ISO_DATE format
    String dateString = "2022-10-12";
    LocalDate date = LocalDate.parse(dateString,
            DateTimeFormatter.ISO_DATE);

    System.out.println(date);
  }
}
Output
2022-10-12

Java Program to Convert String to Date using Custom Formatter

In above program, we used one of the numerous predefined formatters provided by the DateTimeFormatter class called ISO_DATE. However, we can define our own custom formatters also. For Example :

String dateInString = "Mon, 01 May 2022";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, d MMM yyyy", Locale.ENGLISH);
LocalDate dateTime = LocalDate.parse(dateInString, formatter);
Here are the some common date and time patterns:
y – Year (2022; 22)
M – Month in year (July; Jul; 07)
d – Day in month (1-31)
E – Day name in week (Monday, Sunday)
a – AM/PM marker (AM, PM)
H – Hour in day (0-23)
h – Hour in AM/PM (1-12)
m – Minute in hour (0-60)
s – Second in minute (0-60)

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

public class DateTimeCostomFormatter {
  public static void main(String[] args) {
    String string = "20-10-2022"

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
            "dd-MM-yyyy", Locale.ENGLISH);
    LocalDate date = LocalDate.parse(string, formatter);
    System.out.println(date);
  }
}
Output
2022-10-20