1

What would i like to do is get the Monday's date from the current week and subtract it by 1 day. I do not need the time with the date. I've tried below code but it gives me Sunday's date instead of Monday and also time is getting included with the date.Thanks.

Date date = new Date();
        System.out.println(date);
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - c.getFirstDayOfWeek();
        c.add(Calendar.DAY_OF_MONTH, -dayOfWeek);

        Date weekStart = c.getTime();
        System.out.println(weekStart);
Joe
  • 43
  • 1
  • 3
  • 7

1 Answers1

2

I suggest using the JDK8 Date-time APIs which largely simplify these calculations.

LocalDate dt = LocalDate.now()
                        .with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))
                        .minusDays(1);
System.out.println(dt);

The above code gets the current date and adjust it to the current week's Monday or previous week's Monday if the current day is a Sunday. Then subtract 1 day from it, to give the Sunday's date. As LocalDate API deals with only dates, there isn't any need to take care of the time part.

Pallavi Sonal
  • 3,661
  • 1
  • 15
  • 19