GoogleSearchBox

Custom Search

Monday, May 20, 2013

Converting Java.util.date to Java.sql.date using different formatters

/* Converting Java.util.date to Java.sql.date using different formatters  */

String datetimeString = "04/01/2013"; // A String representing your date
java.util.Date result = new java.util.Date();
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
// SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy"); // This format or any other format is not accepted other than above format. Else Throws Exception in thread "main" java.text.ParseException: Unparseable date: "04/01/2013"

result = formatter.parse (datetimeString); // Throws ParseException
System.out.println("Util date = "+result);

java.sql.Date jsqlD = new java.sql.Date(result.getTime()); // Creates a SQL Date to store in Database
   System.out.println("SQL Date = "+jsqlD);

DateFormat df = new SimpleDateFormat("dd MMMM yyyy"); // Formats your date
String formattedDate = df.format(jsqlD);
System.out.println(formattedDate);