Joda-Time:获得一个月的第一个/第二个/最后一个星期日

knu*_*nub 7 java datetime date jodatime

在普通的Java中,我有这个代码来获取本月的最后一个星期日.

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)
Run Code Online (Sandbox Code Playgroud)

什么是干净而优雅的方式来实现相同的结果使用Joda-Time

KrH*_*ert 5

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;
}
}
Run Code Online (Sandbox Code Playgroud)

  • 对。我已经添加了 if 语句。现在应该没问题了。 (2认同)

Ort*_*ier 5

你可以试试这样的东西:

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));
  }
}
Run Code Online (Sandbox Code Playgroud)

输出:

2012-09-02
2012-09-09
2012-09-16
2012-09-23
2012-09-30
Run Code Online (Sandbox Code Playgroud)


小智 5

这是一篇很老的帖子,但可能这个答案会对某人有所帮助。使用替代 Joda-Time 的 java.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));
}
Run Code Online (Sandbox Code Playgroud)