Java – How to get last week and last month with java8

datetimejavajava-8

I have a date and I need to know the last week and last month before the date.

For example,

on July 15, 2018, Its last week was from July 2 to July 8. Its last month was June 1 to June 30.

on July 16, 2018, Its last week was from July 9 to July 15. Its last month was June 1 to June 30.

on July 17, 2018, Its last week was from July 9 to July 15. Its last month was June 1 to June 30.

It is different from get-date-of-first-day-of-week-based-on-localdate-now-in-java-8, my problem is to get last week or last month.

Best Solution

You can use these helper methods.

public static LocalDate[] getPreviousWeek(LocalDate date) {
    final int dayOfWeek = date.getDayOfWeek().getValue();
    final LocalDate from = date.minusDays(dayOfWeek + 6); // (dayOfWeek - 1) + 7
    final LocalDate to = date.minusDays(dayOfWeek);

    return new LocalDate[]{from, to};
}

public static LocalDate[] getPreviousMonth(LocalDate date) {
    final LocalDate from = date.minusDays(date.getDayOfMonth() - 1).minusMonths(1);
    final LocalDate to = from.plusMonths(1).minusDays(1);

    return new LocalDate[]{from, to};
}

There are in fact many ways to write this. I would suggest you to do some exploration on your own.