0

I have some legacy code like this

        final Calendar cal = new GregorianCalendar();
        cal.setTime(today);
        // changed on May-03-2004
        //cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
        if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            cal.add(Calendar.DAY_OF_YEAR, -6);
        } else {
            cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        }
        //System.out.println("Begin of cycle: " + cal.getTime());

And I would like to convert it to use java.time TemporalAdjuster class to hopefully make it more readable.

But I am not really sure how to interpret https://stackoverflow.com/a/1319484/242042 to make the behaviour match.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265

3 Answers3

2

Assuming today really is today's date, then the Java Time API version, using TemporalAdjusters, would be:

LocalDate today = LocalDate.now();

TemporalAdjuster adjuster = TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY);
LocalDate monday = today.with(adjuster);

System.out.println(today + " -> " + monday);

Sample Output

2020-02-01 -> 2020-01-27

2020-02-01 is a Saturday, and 2020-01-27 is the preceding Monday.

Andreas
  • 154,647
  • 11
  • 152
  • 247
1

DayOfWeek implements TemporalAdjuster

I think that your code attempts to set the Calendar object to Monday of the same ISO week, that is, the Monday preceding today if today is not already a Monday (this will not always be the result in all locales, though). It’s really simple when you know how.

    LocalDate today = LocalDate.of(2020, Month.FEBRUARY, 2);
    LocalDate monday = today.with(DayOfWeek.MONDAY);
    System.out.println("Monday of the same week is " + monday + ", a " + monday.getDayOfWeek());

Output from this snippet is:

Monday of the same week is 2020-01-27, a MONDAY

LocalDate always uses the ISO calendar, in which Monday is the first day of the week, so today.with(DayOfWeek.MONDAY) gives you the Monday of the same week, in other words, the previous Monday of today is not already a Monday. GregorianCalendar used the week definition of the default locale, which caused a bit of complication in the code to make sure it would also behave correctly in locales where Sunday is the first day of the week. LocalDate behaves the same in all locales, which is one of the reasons why the code using LocalDate is simpler.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

Ok after playing around and trying different combinations in https://repl.it/@trajano/setCal

The code translates to

  public static LocalDate doIt(LocalDate todayDate) {
    final LocalDate c2;
    if (todayDate.getDayOfWeek() == DayOfWeek.SUNDAY) {
      c2 = todayDate.minusDays(6);
    } else {
      c2 = todayDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
    }
    return c2;

  }
Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265