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);
}
}
}