本文介绍了Joda时间:如何在某个日期间隔获得平日的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个本地日期代表一段时间间隔。现在我必须得到所有星期五的LocalDates,这个间隔包含。最简单的方式来做?
解决方案
解决方案:懒洋洋一个个星期。
import org.joda.time.LocalDate;
import java.util.Iterator;
public class DayOfWeekIterator实现Iterator< LocalDate> {
private final LocalDate end;
private LocalDate nextDate;
public DayOfWeekIterator(LocalDate start,LocalDate end,int dayOfWeekToIterate){
this.end = end;
nextDate = start.withDayOfWeek(dayOfWeekToIterate);
if(start.getDayOfWeek()> dayOfWeekToIterate){
nextDate = nextDate.plusWeeks(1);
}
}
public boolean hasNext(){
return!nextDate.isAfter(end);
}
public LocalDate next(){
LocalDate result = nextDate;
nextDate = nextDate.plusWeeks(1);
返回结果;
}
public void remove(){
throw new UnsupportedOperationException();
}
}
测试
import org.joda.time.DateTimeConstants;
import org.joda.time.LocalDate;
public class DayOfWeekIteratorTest {
public static void main(String [] args){
LocalDate startDate = new LocalDate(2010,12,1 ); // 2010年12月1日
LocalDate endDate = new LocalDate(2010,12,31); // 2010年12月31日
DayOfWeekIterator it = new DayOfWeekIterator(startDate,endDate,DateTimeConstants.FRIDAY);
while(it.hasNext()){
System.out.println(it.next());
}
}
}
I have two LocalDates that represent some time interval. Now i have to get LocalDates of all fridays, that this interval contains.Easiest way to do it?
解决方案
Solution: lazily step by one week.
import org.joda.time.LocalDate;
import java.util.Iterator;
public class DayOfWeekIterator implements Iterator<LocalDate>{
private final LocalDate end;
private LocalDate nextDate;
public DayOfWeekIterator(LocalDate start, LocalDate end, int dayOfWeekToIterate){
this.end = end;
nextDate = start.withDayOfWeek(dayOfWeekToIterate);
if (start.getDayOfWeek() > dayOfWeekToIterate) {
nextDate = nextDate.plusWeeks(1);
}
}
public boolean hasNext() {
return !nextDate.isAfter(end);
}
public LocalDate next() {
LocalDate result = nextDate;
nextDate = nextDate.plusWeeks(1);
return result;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
Test
import org.joda.time.DateTimeConstants;
import org.joda.time.LocalDate;
public class DayOfWeekIteratorTest {
public static void main(String[] args) {
LocalDate startDate = new LocalDate(2010, 12, 1);//1st Dec 2010
LocalDate endDate = new LocalDate(2010, 12, 31);//31st Dec 2010
DayOfWeekIterator it = new DayOfWeekIterator(startDate, endDate, DateTimeConstants.FRIDAY);
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
这篇关于Joda时间:如何在某个日期间隔获得平日的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!