-2

I need to convert the following format of date yyyy-mm-dd to date in format dd/mm/yyyy or dd-mm-yyyy, is it posible. I'm getting unparsable exception.

I have the following code:

String fechaInicial= docudetalle.getfechainicial();
String fechaFinal= docudetalle.getfechafinal();
String fechaEspecial= docudetalle.getfechaespecial();


SimpleDateFormat formatter  = new SimpleDateFormat("dd-mm-yyyy");
Date dateInicial = formatter.parse(fechaInicial);
Date dateFinal = formatter.parse(fechaFinal);
Date dateEspecial = formatter.parse(fechaEspecial);

To which once converted I need to get the difference between the three dates, to show in a table as the amount days passed. How can I get the difference in the dates, I know with calendar instance is much easier to get the difference. Is there is an easier method for this?

Edric
  • 24,639
  • 13
  • 81
  • 91
  • You can check already answered question here. https://stackoverflow.com/questions/18480633/java-util-date-format-conversion-yyyy-mm-dd-to-mm-dd-yyyy – Zedex7 Jun 10 '20 at 19:42
  • Here is a related answer that can help. https://stackoverflow.com/a/62270099/1552534 – WJS Jun 10 '20 at 19:43
  • Please clarify your question: (a) How to __convert date formats__ from `yyyy-MM-dd` to `dd-MM-yyyy` and `dd/MM/yyyy` or (b) calculate __difference in days__ between 3 given dates (which date is the base?). – hc_dev Jun 10 '20 at 20:54
  • 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/). – Ole V.V. Jun 11 '20 at 04:42
  • Welcome to Stack Overflow. When asking about an exception, please paste your stacktrace into the question, nicely formatted as code. Usually that makes it a lot easier to help you. – Ole V.V. Jun 11 '20 at 04:48
  • I am sorry I had to add so many original questions. Part of the reason was that it wasn’t clear to me which one of them you intended to ask. – Ole V.V. Jun 11 '20 at 04:51

1 Answers1

1

Use LocalDate and DateTimeFormatter to manipulate dates.

String source = "2020-04-22";

LocalDate src = LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
String dst = src.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
System.out.println(dst);

// or

dst = src.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
System.out.println(dst);

prints

22/04/2020
22-04-2020
WJS
  • 36,363
  • 4
  • 24
  • 39