2

I am trying to calculate the number of days between two given dates using processing 3. But I am facing a problem with the date library.

import java.text.SimpleDateFormat;
import java.util.Date;

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;


Date epoDate = new Date();  
  Date epo = new Date();
    try {
      epoDate = new SimpleDateFormat("yyyy-mm-dd").parse("2015-01-03");
       epo = new SimpleDateFormat("yyyy-mm-dd").parse("2015-04-23");
    }
    catch (Exception e) {
    }

   ChronoUnit.DAYS.between(epo,epoDate);

}

the problem is with the last line the between function where it says it requires 2 temporal as inputs?

  • 1
    With `ChronoUnit` just use the modern `LocalDate` instead of the poorly designed and outdated `Date` class. `LocalDate` will even parse your strings without any formatter. I recommend you don’t ever use `SimpleDateFormat` and `Date`. The former in particular is notoriously troublesome. – Ole V.V. Feb 07 '19 at 11:58
  • Could be regarded as a duplicate of either [Calculating days between two dates with Java [duplicate\]](https://stackoverflow.com/questions/20165564/calculating-days-between-two-dates-with-java) or [the method in type not applicable for the arguments](https://stackoverflow.com/questions/15285975/the-method-in-type-not-applicable-for-the-arguments). – Ole V.V. Feb 07 '19 at 13:09

1 Answers1

7

Your compiler error can be solved by using the right type. Don't use java.util.Date (as returned by SimpleDateFormat-parser) but use java.time.LocalDate which also offers a direct parse-method recognizing the ISO-format yyyy-MM-dd.

Instead of

new SimpleDateFormat("yyyy-mm-dd").parse("2015-04-23");

use

LocalDate.parse("2015-04-23");

Another thing:

Your final example code ChronoUnit.DAYS.between(epo,epoDate); does not evaluate the result. You should assign the result to a long-primitive for further processing.

About your comment concerning input with one-digit-month

You can use the overloaded parse-method accepting an extra formatter argument this way:

LocalDate.parse("2015-4-23", DateTimeFormatter.ofPattern("uuuu-M-dd"));

It should also work with two-digit-months. And I recommend to assign the formatter object to a static final constant for performance reasons.

Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
  • thanks, it worked. But one more question. Simple Date format could understand 2015-4-23 as 2015-04-23. But localDate seems not to get. is there any way around it ? – Danial Kosarifar Feb 07 '19 at 10:59