Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java change date format from custom date to MM dd yyyy

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();
}   
like image 910
user1070764 Avatar asked Dec 01 '22 22:12

user1070764


1 Answers

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);
like image 58
Matt Ball Avatar answered Dec 20 '22 05:12

Matt Ball