1

I need to find which nth dayOfWeek a particular day is in the month for a date in Java. For example, today is April 20th, 2016 which is the 3rd Wednesday in the month or October 31, 2016 which is the 5th Monday in October. How can I find which number the particular occurrence of a day is in the month?

Gremash
  • 8,158
  • 6
  • 30
  • 44
  • 2
    Do you have _a_ approach before looking for the best? – Savior Apr 20 '16 at 23:32
  • Which version of Java? If less than 8, do you use Joda Time? – fge Apr 20 '16 at 23:33
  • Java 7. Yes, we are using Joda time. – Gremash Apr 20 '16 at 23:36
  • No, I have do not have a solution to the problem yet or I would not ask the question so please don't down vote me because I don't know the answer before I ask the question. – Gremash Apr 20 '16 at 23:38
  • Please do some research before asking. There are a number of Related (possibly duplicate) posts on the right. – Savior Apr 20 '16 at 23:39
  • I have looked at several answers and none of them are the same as my question. There are many questions about the week number in a month but not finding which nth instance of a particular day a date is in a month. – Gremash Apr 20 '16 at 23:40
  • The closest answer I have found is setting a date to the nth of some day of the week, such as the 4th Thursday of the month. I want to do the opposite. I want to know which nth occurrence a particular day is. – Gremash Apr 20 '16 at 23:52
  • I honestly don't know why this is being down voted. It is a valid question. If there is a duplicate that I am not finding please point it out to me. – Gremash Apr 20 '16 at 23:54

1 Answers1

1

Use the get method of the Calendar class.

public static int getOccurenceOfDayInMonth() {
    return Calendar.getInstance().get(Calendar.DAY_OF_WEEK_IN_MONTH);
}

[EDIT]

Here is a solution given any date, rather than the current date.

public static int getOccurenceOfDayInMonth(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);

    return calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH);
}
codewiz
  • 196
  • 1
  • 8
  • This actually works correctly. I generated 1000 days starting from 1-1-2016 and it returns the correct nth occurrence of a particular day of a month for any date. – Gremash Apr 21 '16 at 00:21