Question

I am trying to determine the sequential ordinal number of a weekday in a month in Java. i.e. if a Friday is the first or 3rd friday of a month.

I can not find a simple way after reading all the things I can find on Java Calendar and posts here. One way I can think of is to determine how many days the first week of this month have in this month and then adjust week_of_month based on what day the day in question is. However, it requires a little complicated calculation. Anyone knows a simple solution?

Was it helpful?

Solution

Just take the day of month, subtract 1, divide by 7, then add 1. The first seven days of the month are always the first (Tuesday, Wednesday, ...) whatever day of the week the actual 1st of the month is.

Personally I'd use Joda Time:

public int getWeekOfWeekDay(LocalDate date) {
    return ((date.getDayOfMonth() - 1) / 7) + 1;
}

... but you could do the same using Calendar and fetching the value of the Calendar.DAY_OF_MONTH field.

EDIT: Actually, I've just noticed that for a change, java.util.Calendar is actually simpler than Joda Time - there's a particular field for it! All you need is:

int weekOfWeekDay = calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH);

From the docs for DAY_OF_WEEK_IN_MONTH:

Field number for get and set indicating the ordinal number of the day of the week within the current month. Together with the DAY_OF_WEEK field, this uniquely specifies a day within a month. Unlike WEEK_OF_MONTH and WEEK_OF_YEAR, this field's value does not depend on getFirstDayOfWeek() or getMinimalDaysInFirstWeek(). DAY_OF_MONTH 1 through 7 always correspond to DAY_OF_WEEK_IN_MONTH 1; 8 through 14 correspond to DAY_OF_WEEK_IN_MONTH 2, and so on.

I think I'd probably still use the Joda Time version because it's just a much nicer API all round, but if you're forced to use Calendar, at least you can do this in one shot.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top