-1

I need to fetch a date from database and convert it to util date...

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dob = rst.getString("dob");
java.util.Date DateTemp = new java.sql.Date(formatter.parse(dob).getTime());

But it throws an exception which says unparseable format.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
sudipta.dey
  • 178
  • 1
  • 2
  • 13

3 Answers3

3

Just to answer your question in a simple manner. Your dob value isn't the correct format. The formatter.parse(dob) isn't working because it can't parse (or attempting to extract and change the data to the appropriate format).

Now to change format (from DB format to application format):

final String OLD_FORMAT = "yyyy/MM/dd";
final String NEW_FORMAT = "dd/MM/yyyy";

String oldDateString = rst.getString("dob").replaceAll("-","/");//you to need to replace all the all dashes with slashes
String newDateString;

SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Date d = sdf.parse(oldDateString);
sdf.applyPattern(NEW_FORMAT);
newDateString = sdf.format(d);

Source:

How can I change the date format in Java?

Community
  • 1
  • 1
1

Simply use ResultSet.getDate instead, it returns java.sql.Date which exte nds java.util.Date so you can use it where java.util.Date is requried.

As for the ParseException: ResultSet.getString for DATE column returns date in yyyy-MM-dd format, you should have parsed it with this format.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

In database is stored as yyyy/MM/dd(for e.g. 2013/11/28), and i need to use it in application as dd/MM/yyyy(for e.g 28/11/2013)

Then your first formatter while parsing the string to date should be yyyy/MM/dd and then to format the date object to string should be dd/MM/yyyy !

Moreover , there are appropriate datatypes[DATE,DATETIME etc] to store dates in DB tables , don't use string[CHAR,VARCHAR].

AllTooSir
  • 48,828
  • 16
  • 130
  • 164