简体   繁体   English

如何计算处理3中两个给定日期之间的天数?

[英]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. 我正在尝试使用处理3来计算两个给定日期之间的天数。但是我遇到了日期库的问题。

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? 问题是在函数之间的最后一行,它说它需要2个时间作为输入?

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. 不要使用java.util.Date (由SimpleDateFormat -parser返回),而是使用java.time.LocalDate ,它还提供了一种识别ISO格式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); 您的最终示例代码ChronoUnit.DAYS.between(epo,epoDate); does not evaluate the result. 不评估结果。 You should assign the result to a long-primitive for further processing. 您应该将结果分配给long-primitive以进行进一步处理。

About your comment concerning input with one-digit-month 关于您对一位数月份输入的评论

You can use the overloaded parse-method accepting an extra formatter argument this way: 您可以使用重载的parse-method以这种方式接受额外的formatter参数:

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. 出于性能原因,我建议将formatter对象分配给静态最终常量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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