How to calculate “Friday before” in Java or Groovy?

I need to be able to compute Friday to today in Java or Groovy.

For example, if today is Monday, February 21, “Friday to” will be on Friday, February 18.

And if today was Tuesday, February 1, "Friday to" will be on Friday, January 28.

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

+3
source share
2 answers

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));
+3
source

I would make a method that gave me the number of days that have passed since that 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);
}
+1
source

Source: https://habr.com/ru/post/1792418/


All Articles