How to convert String to Date in java

In this post, we will see how to convert String to Date object in java. It is used when we have formatted String and need to convert it to Date object.You may also check how to convert Date to String

Java program:

package org.arpit.java2blog;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToDateExample {

 public static void main(String[] args) {

  String strDate1 = "25/01/2016";
  String strDate2 = "25-Jan-2014";
  String strDate3 = "Mon, Jan 25 2016";

  /*
   * We will use SimpleDateFormat's parse method to convert String to date. 
   */

  try{

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

   // use parse method of SimpleDateFormat to convert it to date
   // Date object will be returned by parse method
   Date date1 = sdf1.parse(strDate1);

   System.out.println("Date in format dd/MM/yyyy " + sdf1.format(date1));
   
   
   
   SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy");
   Date date2 = sdf2.parse(strDate2);
   System.out.println("Date in format dd-MMM-yyyy: " + sdf2.format(date2));
   
   
   SimpleDateFormat sdf3 = new SimpleDateFormat("E, MMM dd yyyy");
   Date date3 = sdf3.parse(strDate3);
   System.out.println("Date in format E, MMM dd yyyy: " + sdf3.format(date3));

  }catch(ParseException e){

   // This exception will be thrown if string can not be converted to date
   System.out.println("Java String could not be converted to Date: " + e);
  }
 }

}

When you run above program, you will get following output:
Date in format dd/MM/yyyy 25/01/2016
Date in format dd-MMM-yyyy: 25-Jan-2014
Date in format E, MMM dd yyyy: Mon, Jan 25 2016

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012