-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?

6
  • You can check already answered question here. stackoverflow.com/questions/18480633/…
    – Zedex7
    Jun 10, 2020 at 19:42
  • Here is a related answer that can help. stackoverflow.com/a/62270099/1552534
    – WJS
    Jun 10, 2020 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, 2020 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.
    – Anonymous
    Jun 11, 2020 at 4: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.
    – Anonymous
    Jun 11, 2020 at 4:48

1 Answer 1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.