In my Java code, date of birth is retrieved from a database in the format 1999-04-30
. How can I out.println
this in a different format? Like this: 30/04/1999
Asked
Active
Viewed 934 times
-1

Mario Boss
- 1,784
- 3
- 20
- 43

html
- 33
- 3
-
`DateFormat` or if you specific date format you want `SimpleDateFormat` – MadProgrammer Jan 07 '16 at 06:53
-
4[Possible Duplicate](http://stackoverflow.com/questions/4772425/format-date-in-java) – MadProgrammer Jan 07 '16 at 06:54
-
Not quite a duplicate. [That Question](http://stackoverflow.com/questions/4772425/format-date-in-java) is about a String representation of a date-time while this Question is about (a) a date-only value which means the use of date-only classes `java.sql.Date` and `java.time.LocalDate`, and (b) a database value rather than a mere String representation, or so we can presume. – Basil Bourque Jan 07 '16 at 15:35
-
@BasilBourque Yea, it still hasn't worked out. – html Jan 08 '16 at 01:30
-
@html The [Answer by Andreas](http://stackoverflow.com/a/34649135/642706) is correct. Focus on the 2nd part as java.time is a *huge* improvement over the old date-time classes. Edit your Question to expound on the part that is not clear, or comment on his Answer. He is calling getDate on the ResultSet to get a java.sql.Date object (notice the `.sql.`), then calls `toLocalDate` to convert from java.sql to java.time. – Basil Bourque Jan 08 '16 at 07:12
2 Answers
3
You can format date as follows,
SimpleDateFormat format = new SimpleDateFormat();
String DateToStr = format.format(yourDataBaseDate);
format = new SimpleDateFormat("dd/MM/yyyy");
DateToStr = format.format(yourDataBaseDate);
System.out.println(DateToStr);
This is sample date format for your question.

arjun kori
- 1,090
- 2
- 14
- 32
1
Hopefully, the date is retrieved as a java.sql.Date
, which does not have a specific form.
To format such a date value, use:
java.sql.Date birthdate = resultSet.getDate("Birthdate");
SimpleDateFormat dateFmt = new SimpleDateFormat("dd/MM/yyyy");
String text = dateFmt.format(birthdate);
Or, in java.time (Java 8 and later):
java.time.LocalDate birthdate = resultSet.getDate("Birthdate").toLocalDate();
DateTimeFormatter dateFmt = DateTimeFormatter.ofPattern("dd/MM/uuuu");
String text = birthdate.format(dateFmt);

Basil Bourque
- 303,325
- 100
- 852
- 1,154

Andreas
- 154,647
- 11
- 152
- 247