LocalDate today = LocalDate.now(ZoneId.of("Asia/Harbin"));
LocalDate weekStart = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
List<LocalDate> thisWeek = weekStarting(weekStart);
List<LocalDate> lastWeek = weekStarting(weekStart.minusWeeks(1));
List<LocalDate> twoWeeksAgo = weekStarting(weekStart.minusWeeks(2));
List<LocalDate> threeWeeksAgo = weekStarting(weekStart.minusWeeks(3));
System.out.println("3 weeks ago: " + threeWeeksAgo);
System.out.println("2 weeks ago: " + twoWeeksAgo);
System.out.println("Last week: " + lastWeek);
System.out.println("This week: " + thisWeek);
Most of the “magic” happens in my auxiliary method:
private static List<LocalDate> weekStarting(LocalDate date) {
// Might want to validate that date.getDayOfWeek() == DayOfWeek.SUNDAY
List<LocalDate> week = new ArrayList<>(7);
for (int day = 0; day < 7; day++) {
week.add(date);
date = date.plusDays(1);
}
return week;
}
When I ran the code today, it printed:
3 weeks ago: [2018-06-10, 2018-06-11, 2018-06-12, 2018-06-13, 2018-06-14, 2018-06-15, 2018-06-16]
2 weeks ago: [2018-06-17, 2018-06-18, 2018-06-19, 2018-06-20, 2018-06-21, 2018-06-22, 2018-06-23]
Last week: [2018-06-24, 2018-06-25, 2018-06-26, 2018-06-27, 2018-06-28, 2018-06-29, 2018-06-30]
This week: [2018-07-01, 2018-07-02, 2018-07-03, 2018-07-04, 2018-07-05, 2018-07-06, 2018-07-07]
I took it from your code that the first day of the week is Sunday. In many places in the world the week starts on some other day. If you need to take this into account, the code must be modified.
I have stored LocalDate
objects in the lists rather than strings. For most purposes this is a better approach. Format the dates only when you need to present them to a user.
Even for Android I am using and suggesting java.time
, the modern Java date and time API. Will this work? Yes, java.time
works nicely on older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
The Calendar
and SimpleDateFormat
classes that you used (and that come built-in on earlier Android versions too) are long outdated and poorly designed. At least for non-trivial date operations like yours I don’t recommend them.
Links