DateFormat formatter = new SimpleDateFormat(\"MM/dd/yyyy\' \'HH:mm:ss\");
Date d = (Date)formatter.parse(dateTime);
System.out.println(\"date in controller \"+d);
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss");
System.out.println("date in controller"+ df.format(d));
Don't see why the single-qoutes (') are used in the format-string and you also need to catch ParseException
:
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d = new Date();
try {
d = (Date)formatter.parse("12/31/2012 12:13:14");
} catch(ParseException pex) { System.out.println(pex.getMessage()); }
// convert the date into java.sql.Date
java.sql.Date sqldate = new java.sql.Date(d.getTime());
// then put it in the database, something like this:
//resultSet.updateDate("myDateTimeField", sqldate);
Try using format instead of parse.
Date date = new Date();
String DATE_FORMAT = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
System.out.println("Today is " + sdf.format(date) );
Need the output in date format and not as string so as to store the output in datetime field in mysql db
After the statement
Date d = (Date)formatter.parse(dateTime);
java.sql.Date sqldate = new java.sql.Date(d.getTime())
you have got a java.util.Date
object and you can store it as it is in mysql DB (column type : datetime).
However, when you are printing d
, it defaults to the .toString()
implementation. I think you expected some output like Date@ but the toString printed in user readable format thats why the confusion.
You are using d
an object of Date
class, so its toString
method is called that gives the output as Mon Dec 31 16:04:57 IST 2012
.
If you want to display it in the format that you have specified in your SimpleDateFormat
then try using this :
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss");
Date d = (Date)formatter.parse(dateTime);
System.out.println("date in controller "+ formatter.format(d));