0

Hello I am trying to convert sql date format to "dd-MM-yyyy" but in the output I have this unwanted format which shows the current date time (Mon Aug 14 00.00....)

String inputDate  = rs.getDate("BIRTH_DATE").toString();
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date outputDate = formatter.parse(inputDate);
user.setBirthdate(outputDate);
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Nacer
  • 1
  • Call `parse` not on the result of `toString()`, call it on the result of rs.getDate itself. – rzwitserloot Feb 13 '21 at 23:47
  • Incompatible types : Date cannot be converted to String – Nacer Feb 14 '21 at 00:09
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Also see [Insert & fetch java.time.LocalDate objects to/from an SQL database such as H2](https://stackoverflow.com/questions/43039614/insert-fetch-java-time-localdate-objects-to-from-an-sql-database-such-as-h2). – Ole V.V. Feb 14 '21 at 07:50
  • Right, given today’s date (2021-02-14), your code gives Mon Aug 14 00:00:00 CET 19, that’s 2001 years 6 months ago. A surprise alright. – Ole V.V. Feb 14 '21 at 08:42

1 Answers1

0

Dates do not have an inherent format.

java.util.Date inputDate = rs.getDate("BIRTH_DATE");
user.setBirthdate(inputDate);

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
String representation = formatter.format(inputDate);

It would be better to use the new java.time classes: LocalDate, ZonedDateTime and so on.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138