Java change date format from custom date to MM dd yyyy
24,925
Solution 1
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);
Solution 2
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 !
Author by
user1070764
Updated on July 09, 2022Comments
-
user1070764 almost 2 years
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 withSimpleDateFormat
.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(); }
-
Sam Trost about 12 years
-
James Montagne about 12 yearsIf your dates look like
2012-01-20
, why would you use the formatMM/dd/yyyy
in creating yourSimpleDateFormat
? -
Matt Ball about 12 years@JamesMontagne I couldn't have said it better myself.
-
user1070764 about 12 years@JamesMontagne thats not what i actually used that was just the original example i found of one way to do it, your right tho i want month displayed, MMMM.
-
-
user1070764 about 12 yearsThat 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
-
Matt Ball about 12 yearsNeither of these are the problem.
-
Thorn about 12 yearsSince 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.
-
Basil Bourque over 10 yearsFYI, java.sql.Date is a subclass of java.util.Date. No need to convert.
-
Ashok kumar Ganesan over 3 yearswe can remove the second line and use the parser in 4th line to replace the formatter as parser to make it efficient right?