查找Java中某个日期在一天中的第n次出现

问题描述:

我需要找到Java中某个日期在某月中的哪一天。例如,今天是2016年4月20日,它是该月的 3rd 星期三,或2016年10月31日,是10月的 5th 星期一。如何找到特定日期在月份中是哪个数字?

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?

使用Calendar类的get方法

Use the get method of the Calendar class.

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

这是给定日期而不是当前日期的解决方案。

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);
}