Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joda-Time: Get first/second/last sunday of month

In plain Java, I have this code to get the last Sunday of the month.

Calendar getNthOfMonth(int n, int day_of_week, int month, int year) {
    Calendar compareDate = Date(1, month, year);
    compareDate.set(DAY_OF_WEEK, day_of_week);
    compareDate.set(DAY_OF_WEEK_IN_MONTH, n);
    return compareDate;
}
// Usage
Calendar lastSundayOfNovember = getNthOfMonth(-1, SUNDAY, NOVEMBER, 2012)

What is a clean and elegant way to achieve the same result using Joda-Time?

like image 204
knub Avatar asked Sep 11 '12 12:09

knub


3 Answers

This is quite an old post but possibly this answer will help someone. Use the java.time classes that replace Joda-Time.

private static LocalDate getNthOfMonth(int type, DayOfWeek dayOfWeek, int month, int year){
    return LocalDate.now().withMonth(month).withYear(year).with(TemporalAdjusters.dayOfWeekInMonth(type, dayOfWeek));
}
like image 68
naren Avatar answered Nov 09 '22 05:11

naren


public class Time {
public static void main(String[] args) {
    System.out.println(getNthOfMonth(DateTimeConstants.SUNDAY, DateTimeConstants.SEP, 2012));
}


public static LocalDate getNthOfMonth(int day_of_week, int month, int year) {
    LocalDate date = new LocalDate(year, month, 1).dayOfMonth()  
             .withMaximumValue()
             .dayOfWeek()
             .setCopy(day_of_week);
    if(date.getMonthOfYear() != month) {
        return date.dayOfWeek().addToCopy(-7);
    }
    return date;
}
}
like image 26
KrHubert Avatar answered Nov 09 '22 04:11

KrHubert


You can try something like that:

public class Foo {

  public static LocalDate getNthSundayOfMonth(final int n, final int month, final int year) {
    final LocalDate firstSunday = new LocalDate(year, month, 1).withDayOfWeek(DateTimeConstants.SUNDAY);
    if (n > 1) {
      final LocalDate nThSunday = firstSunday.plusWeeks(n - 1);
      final LocalDate lastDayInMonth = firstSunday.dayOfMonth().withMaximumValue();
      if (nThSunday.isAfter(lastDayInMonth)) {
        throw new IllegalArgumentException("There is no " + n + "th Sunday in this month!");
      }
      return nThSunday;
    }
    return firstSunday;
  }


  public static void main(final String[] args) {
    System.out.println(getNthSundayOfMonth(1, DateTimeConstants.SEPTEMBER, 2012));
    System.out.println(getNthSundayOfMonth(2, DateTimeConstants.SEPTEMBER, 2012));
    System.out.println(getNthSundayOfMonth(3, DateTimeConstants.SEPTEMBER, 2012));
    System.out.println(getNthSundayOfMonth(4, DateTimeConstants.SEPTEMBER, 2012));
    System.out.println(getNthSundayOfMonth(5, DateTimeConstants.SEPTEMBER, 2012));
  }
}

Output:

2012-09-02
2012-09-09
2012-09-16
2012-09-23
2012-09-30
like image 41
Ortwin Angermeier Avatar answered Nov 09 '22 06:11

Ortwin Angermeier