3

I need to be able to calculate the "Friday before" today in Java or Groovy.

For example, if today is Monday, February 21, the "Friday before" would be Friday, February 18.

And if today was Tuesday, February 1, the "Friday before" would be Friday, January 28.

What would be the best way to do this? What existing classes can I most effectively leverage?

Michael Brewer-Davis
  • 14,018
  • 5
  • 37
  • 49
Jordan Dea-Mattson
  • 5,791
  • 5
  • 38
  • 53

2 Answers2

3

You can use a loop:

Calendar c = Calendar.getInstance();
while(c.get(Calendar.DAY_OF_WEEK) != Calendar.FRIDAY)
{
    c.add(Calendar.DAY_OF_WEEK, -1)
}

Or

Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_WEEK, -((c.get(Calendar.DAY_OF_WEEK) + 1) % 7));
The Scrum Meister
  • 29,681
  • 8
  • 66
  • 64
1

I would make a method that gave me the number of days that have passed since the given day.

// Uses now by default
public static int daysSince(int day) {
    return daysSince(day, Calendar.getInstance());
}

// Gives you the number of days since the given day of the week from the given day.
public static int daysSince(int day, Calendar now) {
    int today = now.get(Calendar.DAY_OF_WEEK);
    int difference = today - day;
    if(difference <= 0) difference += 7;
    return difference;
}

// Simple use example
public static void callingMethod() {
    int daysPassed = daysSince(Calendar.FRIDAY);
    Calendar lastFriday = Calendar.getInstance().add(Calendar.DAY_OF_WEEK, -daysPassed);
}
Joel
  • 16,474
  • 17
  • 72
  • 93