How to calculate the number of days between two given dates in processing 3?

Danial Kosarifar :

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?

Meno Hochschild :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=114930&siteId=1