简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM