0

I manage to do it easlily in java 8:

public static Date getFourthTuesdayOfMay(int year){
        LocalDate date = LocalDate.of(year, Month.MAY, 1);
        LocalDate fourthTuesdayOfMay = date.with(dayOfWeekInMonth(4, DayOfWeek.TUESDAY));
        return Date.from(fourthTuesdayOfMay.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
    }

The problem is I need to do it in java 7 ... but can't figure out how.

Answer is:

Calendar date = Calendar.getInstance ();
        date.set(Calendar.DAY_OF_WEEK,Calendar.TUESDAY);
        date.set(Calendar.MONTH, Calendar.MAY);
        date.set(Calendar.WEEK_OF_MONTH, 4);
        date.set(Calendar.YEAR, year);
        date.set(Calendar.HOUR, 0);
        date.set(Calendar.MINUTE, 0);
        date.set(Calendar.SECOND, 0);
        date.set(Calendar.MILLISECOND, 0);

        return date.getTime();
Tyvain
  • 2,640
  • 6
  • 36
  • 70
  • 2
    If you use the [Joda-Time](http://www.joda.org/joda-time/) library, you won't have to change your code much at all. – 4castle Jun 12 '17 at 22:05
  • 2
    @4castle Or [ThreeTen](http://www.threeten.org/threetenbp/) – OneCricketeer Jun 12 '17 at 22:10
  • You could iterate from the start of the month to the first Tuesday, then add 21 days, but it's going to be much easier to use a library as mentioned above. – Jason Jun 12 '17 at 22:14

1 Answers1

0

In java 7 one needs to use Calendar for a pure Java SE solution. (Joda being almost java 8.)

public static Date getFourthTuesdayOfMay(int year) {
    Calendar calendar = Calendar.getInstance();
    int monthDay = 1;
    calendar.set(year, Calendar.MAY, monthDay);
    while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.TUESDAY) {
        ++monthDay;
        calendar.set(Calendar.DAY_OF_MONTH, monthDay);
    }
    // monthDay = 1, ..., 7
    monthDay += 3 * 7; // At most 28 <= 31
    calendar.set(Calendar.DAY_OF_MONTH, monthDay);
    return calendar.getTime();
}

As the locale is not specified, one could get a non-Gregorian calendar, so maybe add Locale.FRANCE to getInstance. The loop for day-of-week could be prevented by modulo 7 but that is not as readable.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • 1
    You don't clear time of day. Also, it seems a bit excessive, doing all those `get` and `set` calls in a loop, when it can be done like this: `calendar.set(year, Calendar.MAY, 1); calendar.add(Calendar.DAY_OF_MONTH, (Calendar.TUESDAY + 7 - calendar.get(Calendar.DAY_OF_WEEK)) % 7 + 21);`, but I guess "readable" is a matter of opinion. – Andreas Jun 12 '17 at 22:35
  • @Andreas valuable comment; I prefer the more functional and terse style too in my code. But it is harder to comment. And negative modulo (+7) and such. Thanks for the shorter version. – Joop Eggen Jun 13 '17 at 19:40