Java:列出开始日期和结束日期之间的日期 [英] Java: List the dates between a start and end date
问题描述
我正在尝试输入开始日期,结束日期,并获取介于两者之间的所有日期.我有需要的格式,已经准备好 Joda-Time . ..过去,我被困住了.我已经包括了我正在做的事情,以及不做的事情.
I'm trying to enter a start date, an end date, and obtain all the dates in between. I have the formatting where I need it, I have Joda-Time ready to go, but...past that, I'm stuck. I've included what I have working, as well as what is not going.
到目前为止,我有以下代码(有效):
So far, I have the following code (working):
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
DateFormat sysDate = new SimpleDateFormat("ddMMyyyy");
//Get Start Date
Date str_date = jXDatePicker1.getDate();
jXDatePicker1.setFormats(dateFormat);
String startDate = sysDate.format(jXDatePicker1.getDate());
//Get End Date
Date end_date = jXDatePicker2.getDate();
jXDatePicker2.setFormats(dateFormat);
String endDate = sysDate.format(jXDatePicker2.getDate());
这是我要实现的目标,但没有成功:
And here's what I'm trying to implement but to no success:
List<LocalDate> dates = new ArrayList<LocalDate>();
int days = Days.daysBetween(startDate, endDate).getDays();
for (int i=0; i < days; i++) {
LocalDate d = startDate.withFieldAdded(DurationFieldType.days(), i);
dates.add(d);
}
先谢谢您.
推荐答案
我不确定int days = Days.daysBetween(startDate, endDate).getDays();
是否可以工作,假设startDate
和endDate
仍然是String
s
I'm not sure if int days = Days.daysBetween(startDate, endDate).getDays();
will work, assuming the startDate
and endDate
are still String
s
相反,您应该改用str_date
和end_date
值,也许更像是...
Instead, you should use the str_date
and end_date
values instead, maybe something more like...
int days = Days.daysBetween(new LocalDate(str_date), new LocalDate(end_date)).getDays();
System.out.println(days);
尝试并记住,通常日期/时间的格式"是无关紧要的,相反,您想使用(日期/时间的)实际值,并且需要显示时,然后根据需要进行格式化
Try and remember, in general the "format" of the date/time is irrelevant, instead, you want to work with the actual values (of the date/time) and when you need to display, then format then as required
通常我只是在日期早于结束日期时不断循环播放,就像...
Normally I just keep looping while the date is before the end date, something like...
Random rnd = new Random();
LocalDate start = new LocalDate(2015, DateTimeConstants.SEPTEMBER, 1);
LocalDate end = start.plusDays(rnd.nextInt(200));
List<LocalDate> dates = new ArrayList<>(25);
dates.add(start);
while (start.isBefore(end)) {
start = start.plusDays(1);
dates.add(start);
}
for (LocalDate date : dates) {
System.out.println(date);
}
从开始日期到结束日期,这是一个包容性,并且本示例仅生成从开始日期到未来随机天数的日期列表
This is inclusive, from the start date to the end date and this example simply generates a list of dates from the start date to a random number of days in the future
这篇关于Java:列出开始日期和结束日期之间的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!