查找Java中某个日期在一天中的第n次出现 [英] Find which nth occurrence of a day in a month for a date in Java

查看:81
本文介绍了查找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);
}

这篇关于查找Java中某个日期在一天中的第n次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆