如何在java中获取两个日期之间的日期列表 [英] how to get a list of dates between two dates in java

查看:27
本文介绍了如何在java中获取两个日期之间的日期列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个介于开始日期和结束日期之间的日期列表.

I want a list of dates between start date and end date.

结果应该是所有日期的列表,包括开始和结束日期.

The result should be a list of all dates including the start and end date.

推荐答案

早在 2010 年,我就建议为此使用 Joda-Time.

请注意,Joda-Time 现在处于维护模式.从 1.8 (2014) 开始,您应该使用 java.time.

Note that Joda-Time is now in maintenance mode. Since 1.8 (2014), you should use java.time.

一次添加一天,直到到达结束日期:

Add one day at a time until reaching the end date:

int days = Days.daysBetween(startDate, endDate).getDays();
List<LocalDate> dates = new ArrayList<LocalDate>(days);  // Set initial capacity to `days`.
for (int i=0; i < days; i++) {
    LocalDate d = startDate.withFieldAdded(DurationFieldType.days(), i);
    dates.add(d);
}

实现自己的迭代器也不会太难,那样会更好.

It wouldn't be too hard to implement your own iterator to do this as well, that would be even nicer.

这篇关于如何在java中获取两个日期之间的日期列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆