How to Convert String Date to Date in Java

Last modified date

This is the most commonly asked question in Java date that how to convert simple String date to date and perform some date related
conditions in Java. So in here given example i have explained with various example to convert String date to Java Date.
So before starting with the step by step process you must identify the placement of your String date
Example: If your date is something like

String sd1="31/12/2018";
String sd2="12-31-2018";

The above given sd1 date 31/12/2018 format is dd/MM/yyyy and the sd2 date 12-31-2018 format is MM-dd-yyyy
How To Convert String Date to Date in Java Step by Step
1. Convert the given String date using SimpleDateFormat

SimpleDateFormat sdf1=new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat sdf2=new SimpleDateFormat("MM-dd-yyyy");

2. Make sure your SimpleDateFormat pattern is same of you String Date

String sd1="31/12/2018"; // dd/MM/yyyy
SimpleDateFormat sdf1=new SimpleDateFormat("dd/MM/yyyy");

String sd2="12-31-2018"; // MM-dd-yyyy
SimpleDateFormat sdf2=new SimpleDateFormat("MM-dd-yyyy");

If the SimpleDateFormat pattern does not match with String date then it will throw an exception

Exception in thread "main" java.text.ParseException: Unparseable date

3. Simple Parse the String Date to date using SimpleDateFormat

Date d1=sdf1.parse(sd1);
Date d2=sdf2.parse(sd2);

4. Once the parse is done sucessfully your Date d1 holds the perfect Java date,it can be used for further Date operation
without any problem.

Java Working code converting Various String Date to Java Date

package DataStructureAndAlgorthms;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class ConvertStringToDate {

  public static void main(String[] args) {
    try {
      // Sample String Dates and its format
      String sd1="31/12/2018";	//	dd/MM/yyyy
      String sd2="12-31-2018";	//	MM-dd-yyyy
      String sd3="31.12.2018";	//	dd.MM.yyyy
      String sd4="2018-31-12";	//	yyyy-dd-MM
      String sd5="31-12-2018";	//	dd-MM-yyyy
      
      SimpleDateFormat sdf1=new SimpleDateFormat("dd/MM/yyyy");
      SimpleDateFormat sdf2=new SimpleDateFormat("MM-dd-yyyy");
      SimpleDateFormat sdf3=new SimpleDateFormat("dd.MM.yyyy");
      SimpleDateFormat sdf4=new SimpleDateFormat("yyyy-dd-MM");
      SimpleDateFormat sdf5=new SimpleDateFormat("dd-MM-yyyy");
      
      Date d1=sdf1.parse(sd1); // now you can change this date format to custom format like yyyy-MM-dd
      Date d2=sdf2.parse(sd2);
      Date d3=sdf3.parse(sd3);
      Date d4=sdf4.parse(sd4);
      Date d5=sdf5.parse(sd5);
      
      System.out.println(d1);
      System.out.println(d2);
      System.out.println(d3);
      System.out.println(d4);
      System.out.println(d5);
      
    } catch (Exception e) {
      e.printStackTrace();
      // TODO: handle exception
    }  
  }
}

 

intactabode