keeplearning
keeplearning

Reputation: 379

How to get a Date object from String

DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss");
Date d = (Date)formatter.parse(dateTime);
System.out.println("date in controller "+d);

I get the output as

date in controller Mon Dec 31 16:04:57 IST 2012

Please suggest a method to output the date in MM/dd/yyyy HH:mm:ss format. Need the output in date format and not as string so as to store the output in datetime field in mysql db

Upvotes: 5

Views: 4913

Answers (5)

Tariq M Nasim
Tariq M Nasim

Reputation: 1278

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

Upvotes: 1

Rahul
Rahul

Reputation: 16355

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.

Upvotes: 2

Dinesh Vadivelu
Dinesh Vadivelu

Reputation: 29

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

Upvotes: 0

Matt
Matt

Reputation: 4785

SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss");
System.out.println("date in controller"+ df.format(d));

Upvotes: 0

Abubakkar
Abubakkar

Reputation: 15664

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

Upvotes: 1

Related Questions