【发布时间】:2020-03-19 06:24:25
【问题描述】:
我从控制台读取了 2 个格式为 yyyy-mm-dd 的字符串,我想打印它们之间的天数。但是,当我尝试打印结果时,出现了一个奇怪的错误
- Error:(12, 43) java: no suitable method found for between(java.util.Date,java.util.Date)
method java.time.temporal.TemporalUnit.between(java.time.temporal.Temporal,java.time.temporal.Temporal) is not applicable
(argument mismatch; java.util.Date cannot be converted to java.time.temporal.Temporal)
method java.time.temporal.ChronoUnit.between(java.time.temporal.Temporal,java.time.temporal.Temporal) is not applicable
(argument mismatch; java.util.Date cannot be converted to java.time.temporal.Temporal)
我不知道为什么?
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Scanner;
public class Tester {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine(); // for example - 2017-02-01
String b = sc.nextLine(); // 2017-10-05
Date d1 = new Date(String.format(a, "yyyy-mm-dd"));
Date d2 = new Date(String.format(b, "yyyy-mm-dd"));
System.out.println(ChronoUnit.DAYS.between(d1,d2));
}
}
【问题讨论】:
-
您能告诉我们错误吗?最好编辑您的问题并粘贴错误和堆栈跟踪。
-
它显示什么样的错误?
-
尝试使用 SimpleDateFormat - 看看这个教程baeldung.com/java-simple-date-format
-
我建议你不要使用
Date。该课程设计不良且早已过时。而是使用来自java.time, the modern Java date and time API 的LocalDate。还有@ScaryWombat 我也建议不要使用SimpleDateFormat它出了名的麻烦。 -
如果使用 Java 9 或更高版本,我推荐the excellent answer by Meno Hochschild here。