4

I am trying to convert a String value that is stored in a database,for example "2012-01-20", to be in the format January 20, 2012.

I have seen some examples, but they are using Date which works with SimpleDateFormat.

As an example here is one way I tried but the "try" always fails and the result is null

DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate=null;

try {

    convertedDate = df.parse(datePlayed);                   

} catch(ParseException e){
    e.printStackTrace();
}   
bruno
  • 2,213
  • 1
  • 19
  • 31
user1070764
  • 71
  • 1
  • 2
  • 5

3 Answers3

18

In short, you're not using the right format for parsing. You need to use two DateFormat instances; one for parsing and one for formatting.

DateFormat parser = new SimpleDateFormat("yyyy-MM-dd");
DateFormat formatter = new SimpleDateFormat("MMM dd, yyyy");
Date convertedDate = parser.parse(datePlayed);
String output = formatter.format(convertedDate);
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • That worked! now i realize what i had to do with setting up the parser first to recognize my pattern. Thank you very much for the fast response – user1070764 Apr 25 '12 at 03:02
  • we can remove the second line and use the parser in 4th line to replace the formatter as parser to make it efficient right? – Ashok kumar Ganesan Nov 23 '20 at 05:53
1
Date da = new Date();
SimpleDateFormat ft = new SimpleDateFormat("E, dd/MM/yyyy !");
System.out.println("Update : " + ft.format(da));

You can change your date style do you want at: E, dd/MM/yyyy !

Good luck !

ByteHamster
  • 4,884
  • 9
  • 38
  • 53
tanpham
  • 101
  • 1
  • 1
0

If the Date is read from a Database, then store it as a java.sql.Date. You can then use SimpleDateFormat on it, maybe after converting to java.util.Date. From the ResultSet object, you can extract Dates.

If what you meant is that you are given a date in text that was extracted from a DB by someone else and you are stuck with it. Try using:

 DateFormat df = new SimpleDateFormat("yyyy-MM-dd");  
 df.setLenient(true);  
 convertedDate = df.parse(datePlayed.trim() );

Also try displaying the text you are parsing before you parse to make sure the datePlayed value is what you expect. With parseInt, an extra space before or after the data will cause an error, so calling trim() removes extra spaces.

Thorn
  • 4,015
  • 4
  • 23
  • 42
  • Neither of these are the problem. – Matt Ball Apr 25 '12 at 03:06
  • Since we didn't see his actual input, we don't know for sure what the problem is. You an I offered solutions to the most likely causes of the problem. – Thorn Apr 25 '12 at 03:11
  • FYI, [java.sql.Date](http://docs.oracle.com/javase/7/docs/api/java/sql/Date.html) is a subclass of [java.util.Date](http://docs.oracle.com/javase/7/docs/api/java/util/Date.html). No need to convert. – Basil Bourque Dec 07 '13 at 09:00