How to get ordinal Weekdays in a Month

泄露秘密 提交于 2019-11-29 17:04:38

Here's a utility method that does that, using DateUtils from Apache Commons / Lang:

/**
 * Get the n-th x-day of the month in which the specified date lies.  
 * @param input the specified date
 * @param weeks 1-based offset (e.g. 1 means 1st week)
 * @param targetWeekDay (the weekday we're looking for, e.g. Calendar.MONDAY
 * @return the target date
 */
public static Date getNthXdayInMonth(final Date input,
    final int weeks,
    final int targetWeekDay){

    // strip all date fields below month
    final Date startOfMonth = DateUtils.truncate(input, Calendar.MONTH);
    final Calendar cal = Calendar.getInstance();
    cal.setTime(startOfMonth);
    final int weekDay = cal.get(Calendar.DAY_OF_WEEK);
    final int modifier = (weeks - 1) * 7 + (targetWeekDay - weekDay);
    return modifier > 0
        ? DateUtils.addDays(startOfMonth, modifier)
        : startOfMonth;
}

Test code:

// Get this month's third thursday
System.out.println(getNthXdayInMonth(new Date(), 3, Calendar.THURSDAY));

// Get next month's second wednesday:
System.out.println(getNthXdayInMonth(DateUtils.addMonths(new Date(), 1),
    2,
    Calendar.WEDNESDAY)
);

Output:

Thu Nov 18 00:00:00 CET 2010
Wed Dec 08 00:00:00 CET 2010


And here's a JodaTime version of the same code (I've never used JodaTime before, so there's probably a simpler way to do it):

/**
 * Get the n-th x-day of the month in which the specified date lies.
 * 
 * @param input
 *            the specified date
 * @param weeks
 *            1-based offset (e.g. 1 means 1st week)
 * @param targetWeekDay
 *            (the weekday we're looking for, e.g. DateTimeConstants.MONDAY
 * @return the target date
 */
public static DateTime getNthXdayInMonthUsingJodaTime(final DateTime input,
    final int weeks,
    final int targetWeekDay){

    final DateTime startOfMonth =
        input.withDayOfMonth(1).withMillisOfDay(0);
    final int weekDay = startOfMonth.getDayOfWeek();
    final int modifier = (weeks - 1) * 7 + (targetWeekDay - weekDay);
    return modifier > 0 ? startOfMonth.plusDays(modifier) : startOfMonth;
}

Test Code:

// Get this month's third thursday
System.out.println(getNthXdayInMonthUsingJodaTime(new DateTime(),
    3,
    DateTimeConstants.THURSDAY));

// Get next month's second wednesday:
System.out.println(getNthXdayInMonthUsingJodaTime(new DateTime().plusMonths(1),
    2,
    DateTimeConstants.WEDNESDAY));

Output:

2010-11-18T00:00:00.000+01:00
2010-12-08T00:00:00.000+01:00

  public static Date getDate(int day, int weekNo, int month, int year) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.DATE,1);
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.MONTH, month);
    for (int i = 0; i < 31; i++) {
        if (cal.get(Calendar.WEEK_OF_MONTH) == weekNo
                && cal.get(Calendar.DAY_OF_WEEK) == day) {
            return cal.getTime();
        }
        cal.add(Calendar.DATE,1);
    }
    return null;
  }

Calling code

System.out.println(""+getDate(Calendar.MONDAY, 2, Calendar.DECEMBER,2010));

Output

Mon Dec 06 15:09:00 IST 2010
Basil Bourque

tl;dr

LocalDate firstFridayThisMonth =
    LocalDate.now( ZoneId.of( "America/Montreal" ) )
             .with( TemporalAdjusters.firstInMonth( DayOfWeek.FRIDAY ) )

Using java.time

The other Answers are now outdated. The troublesome old date-time classes (Date, Calendar, etc.) are now legacy, supplanted by the java.time classes.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

TemporalAdjuster

The TemporalAdjuster interface provides for manipulating date-time values. The java.time classes use immutable objects, so the result is always a fresh new object with values based on the original.

The TemporalAdjusters class (note plural name) provides several handy implementations. Amongst those are ones to get ordinal day-of-week within the month: firstInMonth(), lastInMonth(), and dayOfWeekInMonth(). All of these take an argument of a DayOfWeek enum object.

LocalDate firstFridayOfThisMonth = 
    today.with(
        TemporalAdjusters.firstInMonth( DayOfWeek.FRIDAY ) 
    )
;

…and…

LocalDate secondMondayOfThisMonth = 
    today.with(
        TemporalAdjusters.dayOfWeekInMonth( 2 , DayOfWeek.MONDAY ) 
    )
;

…and…

LocalDate thirdWednesdayOfNextMonth = 
    today.plusMonths( 1 )
         .with(  
             TemporalAdjusters.dayOfWeekInMonth( 3 , DayOfWeek.WEDNESDAY )  
         )
;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Calendar cal = Calendar.getInstance();
int dayofweek = cal.get(Calendar.DAY_OF_WEEK);

this should do what you want.
edit: with some more calculate steps, you could have result :) (sorry for confuse your title)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!