First, you should not get your date as a String from your Postgres database. You should get it as an object of the type representing the date.
Secondly, while in 2013 the use of Date and SimpleDateFormat was commonplace and reasonable, the days passed and the new and better date and time classes came out and became generally accepted. IMHO no one else should use the old classes, and I consider them obsolete.
To get a LocalDate object from a ResultSet from your database:
LocalDate da = yourResultSet.getObject(3, LocalDate.class);
(I assume the date is listed in column 3 in the request).
To format it in dd-MM-yyyy :
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-uuuu"); String strDateTime = da.format(formatter); System.out.println("==String date is : " + strDateTime);
This will give a result, for example
==String date is : 21-02-2013
Finally, if you have a line, as in the question, and you want to reformat it to the desired format:
String strDate = "2013-02-21"; LocalDate da = LocalDate.parse(strDate); System.out.println("==Date is ==" + da);
Will print
==Date is ==2013-02-21
I use the fact that the string complies with the ISO 8601 date standard, which is the default for modern date and time classes. Therefore, in this case, we do not need an explicit formatter for parsing, as well as for parsing other formats.
Formatting to the desired format is exactly the same as before.
An example of a problem with old classes
On my computer, the output from the code in the question
==Date is ==Tue Aug 06 00:00:00 CET 26 ==String date is : 06-08-0026
You obviously get the wrong result, and you donβt understand what happened. It wasnβt good that you parsed the db date string, 2013-02-21 , with the formatting you intended for the new string, dd-MM-yyyy . Thus, it is analyzed as 2013 February 21st. Are there days in February in February? There is no problem with SimpleDateFormat with default settings, it just keeps counting the days in the following months and years and ends on August 6 five and a half years later, but is still very early in history.
If we try to do similarly to modern classes:
LocalDate.parse(strDate, formatter);
- we get java.time.format.DateTimeParseException: Text '2013-02-21' could not be parsed at index 2 . This is due to the fact that the formatter indicated a 2-digit day, so when after parsing two digits there are more digits in the input line, an error appears and is reported as such. I consider this behavior more correct and useful.