First, you shouldn’t get your date as a String
from your Postgres database. You should get it as an object of a type representing a date.
Second, while in 2013 use of Date
and SimpleDateFormat
were commonplace and reasonable, days have gone by and new and better date and time classes have come out and have come into common use. IMHO no one should use the old classes anymore and I consider them long outdated.
To get a LocalDate
object from your ResultSet
from your database:
LocalDate da = yourResultSet.getObject(3, LocalDate.class);
(I am assuming the date is in column 3 in the query).
To format it into dd-MM-yyyy
:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
String strDateTime = da.format(formatter);
System.out.println("==String date is : " + strDateTime);
This would give output like
==String date is : 21-02-2013
Finally, in case you have got a string like in the question and want to reformat it into your desired format:
String strDate = "2013-02-21";
LocalDate da = LocalDate.parse(strDate);
System.out.println("==Date is ==" + da);
This prints
==Date is ==2013-02-21
I am taking advantage of the fact that the string matches the ISO 8601 standard date format that is the default for the modern date and time classes. So in this case we don’t need an explicit formatter for parsing, as we would for parsing other formats.
Formatting into your desired format happens precisely as before.
An example of the trouble with the old classes
On my computer the output from the code in the question is
==Date is ==Tue Aug 06 00:00:00 CET 26
==String date is : 06-08-0026
You are clearly getting a wrong result, and you are getting no clue what was wrong. What was wrong was that you were parsing your db date string, 2013-02-21
, with the formatter you intended for the new string, dd-MM-yyyy
. So it is parsed as the 2013th February 21 AD. There aren’t 2013 days in february? No problem to a SimpleDateFormat
with default settings, it just continues counting days into the following months and years and ends up at August 6 five and a half years later, but still very early in history.
If we try doing similarly with the 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 because the formatter indicated 2-digit day, so when after parsing two digits there are more digits in the input string, it’s an error and is reported as such. I consider this behaviour more correct and more helpful.