-1

Consider the code below. I'm calculating the differences in days between two dates. However, the output is sometimes invalid. Does anyone know how this could be? Don't be concerned about leap years.

SimpleDateFormat myFormat = new SimpleDateFormat("dd-MM-yyyy")           
Date date1 = (Date) myFormat.parse(datenow);
Date date2 = (Date) myFormat.parse(factuurdatumList.get(i));
long difference = date1.getTime() - date2.getTime();
System.out.println("Days: " + TimeUnit.DAYS.convert(difference, TimeUnit.MILLISECONDS));
int openstaand = (int) TimeUnit.DAYS.convert(difference, TimeUnit.MILLISECONDS);
Not Dutch
  • 49
  • 7
  • 1
    what are the inputs and the outputs and what it should be ? – Youcef LAIDANI Jun 23 '18 at 19:31
  • 1
    *"output is sometimes invalid"* In what way? Show example. But I'll bet that the invalid output is caused by dates crossing a Daylight Savings Time transition. – Andreas Jun 23 '18 at 19:38
  • 1
    Please read [How do I ask a question that is answerable?](http://stackoverflow.com/help/how-to-ask) before attempting to ask more questions so you will be better prepared and able to ask a question that will be well received and more importantly **answerable**. –  Jun 23 '18 at 20:25
  • 1
    I recommend you avoid the `SimpleDateFormat` class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jun 23 '18 at 21:34

1 Answers1

2

Update: Changed day and month to allow single digit, and added example dates and output.

Easy enough, if you stop using the old out-dated Date class.

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("d-M-uuuu");
LocalDate date1 = LocalDate.parse("23-6-2018", fmt);
LocalDate date2 = LocalDate.parse("23-12-2018", fmt);
long days = ChronoUnit.DAYS.between(date1, date2);
System.out.println("Days: " + days);

Output

Days: 183

See this code run live at IdeOne.com.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Andreas
  • 154,647
  • 11
  • 152
  • 247