Convert String to Date in Java

JavaObject Oriented ProgrammingProgramming

Let’s say the following are our strings −

String date1 ="11/10/2018";
String date2 = "15-Mar-2019 21:11:35";

Now, convert the above string to dates −

SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat dateFormat2 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
Date formattedDate1 = dateFormat1.parse(date1);
Date formattedDate2 = dateFormat2.parse(date2);

Example

Following is the program to convert String to Date in Java −

 Live Demo

import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
   public static void main(String[] args)throws Exception {
      String date1 ="11/10/2018";
      String date2 = "15-Mar-2019 21:11:35";
      SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd/MM/yyyy");
      SimpleDateFormat dateFormat2 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
      Date formattedDate1 = dateFormat1.parse(date1);
      Date formattedDate2 = dateFormat2.parse(date2);
      System.out.println(formattedDate1);
      System.out.println(formattedDate2);
   }
}

Output

Thu Oct 11 00:00:00 UTC 2018
Fri Mar 15 21:11:35 UTC 2019
raja
Published on 26-Sep-2019 16:29:57
Advertisements