gpt4 book ai didi

java - 在java中打印2个日期之间的所有日期,特殊情况

转载 作者:行者123 更新时间:2023-12-01 17:53:54 24 4
gpt4 key购买 nike

我从控制台读取了 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));
}
}

最佳答案

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Scanner;

public class StackOverFlow {
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine(); // for example - 2017-02-01
String b = sc.nextLine(); // 2017-10-05
List<Date> datesInRange = new ArrayList<>();
Date d1 = new SimpleDateFormat("yyyy-MM-dd").parse(a);
Date d2 = new SimpleDateFormat("yyyy-MM-dd").parse(b);
Calendar calendar = new GregorianCalendar();
calendar.setTime(d1);

Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(d2);

while (calendar.before(endCalendar)) {
Date result = calendar.getTime();
datesInRange.add(result);
calendar.add(Calendar.DATE, 1);
}
System.out.println(datesInRange);

}
}

关于java - 在java中打印2个日期之间的所有日期,特殊情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60751926/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com