Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 获取给定开始日期和结束日期的日期列表_Java_Loops_Date - Fatal编程技术网

Java 获取给定开始日期和结束日期的日期列表

Java 获取给定开始日期和结束日期的日期列表,java,loops,date,Java,Loops,Date,给定两个日期(以M,YYYY的形式表示的开始日期和结束日期),我想制作一个arraylist,其中每个元素都是以M,yyy的形式表示的介于开始日期和结束日期之间的日期 例如,给定日期102010和22011,我的列表应如下所示: list = {(10,2010),(11,2010),(12,2010),(1,2011),(2,2011)}; 我可以创建一个while循环(whilestartyearym.plusMonths(1)) .限制(月数介于(从,到)+1之间) .collect(t

给定两个日期(以M,YYYY的形式表示的开始日期和结束日期),我想制作一个arraylist,其中每个元素都是以M,yyy的形式表示的介于开始日期和结束日期之间的日期

例如,给定日期102010和22011,我的列表应如下所示:

list = {(10,2010),(11,2010),(12,2010),(1,2011),(2,2011)};
我可以创建一个while循环(whilestartyear
但我觉得必须有一种更有效的方法来处理这件事,因为这需要在开始月份和结束年份进行多次检查。有没有更好的解决方案,我没有看到?

将日期存储为对象而不是年、月的“对”会更有意义。例如,在API(Java 8及更高版本)中使用类:

YearMonth from=YearMonth.of(2010,10);
年月日至=年月日(2011年,2);
List=newarraylist();
for(YearMonth ym=from;!ym.isAfter(to);ym=ym.plusMonths(1)){
列表。添加(ym);
}
或者使用(不确定在这种情况下是否更干净):

List List=Stream.iterate(from,ym->ym.plusMonths(1))
.限制(月数介于(从,到)+1之间)
.collect(toList());

@assylias JAVA,对不起,我忘了把它包括在内。
YearMonth from = YearMonth.of(2010, 10);
YearMonth to = YearMonth.of(2011, 2);
List<YearMonth> list = new ArrayList<> ();

for (YearMonth ym = from; !ym.isAfter(to); ym = ym.plusMonths(1)) {
  list.add(ym);
}
List<YearMonth> list = Stream.iterate(from, ym -> ym.plusMonths(1))
                             .limit(MONTHS.between(from, to) + 1)
                             .collect(toList());