For reference, the current date used to formulate the output was Wednesday, 22nd July, 2015 (22/07/2015)
Java 8
LocalDate ld = LocalDate.now();
LocalDate sunday = ld.minusDays(ld.getDayOfWeek().getValue());
LocalDate tommorrow = ld.plusDays(1);
LocalDate date = sunday;
while (date.isBefore(tommorrow)) {
System.out.println(date);
date = date.plusDays(1);
}
Prints
2015-07-19
2015-07-20
2015-07-21
2015-07-22
As an alternative
(Which will basically work for all the other mentioned APIs) you could simply walk backwards from today...
LocalDate date = LocalDate.now();
do {
System.out.println(date);
date = date.minusDays(1);
} while (date.getDayOfWeek() != DayOfWeek.SATURDAY);
Prints
2015-07-22
2015-07-21
2015-07-20
2015-07-19
JodaTime
LocalDate now = LocalDate.now();
LocalDate sunday = now.minusDays(5).withDayOfWeek(DateTimeConstants.SUNDAY);
LocalDate tommorrow = now.plusDays(1);
LocalDate date = sunday;
while (date.isBefore(tommorrow)) {
System.out.println(date);
date = date.plusDays(1);
}
Prints
2015-07-19
2015-07-20
2015-07-21
2015-07-22
Calendar
As a last resort. Remember though, Calendar
carries time information, so using before
, after
and equals
may not always do what you think they should...
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.SUNDAY);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
Calendar today = Calendar.getInstance();
while (cal.before(today)) {
System.out.println(cal.getTime());
cal.add(Calendar.DATE, 1);
}
Prints
Sun Jul 19 15:01:49 EST 2015
Mon Jul 20 15:01:49 EST 2015
Tue Jul 21 15:01:49 EST 2015
Wed Jul 22 15:01:49 EST 2015
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…