7

在纯 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)

什么是使用 达到相同结果的干净优雅的方法Joda-Time

4

7 回答 7

6

这是一篇相当老的帖子,但可能这个答案会对某人有所帮助。使用替换 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));
}
于 2017-08-21T08:45:28.530 回答
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;
}
}
于 2012-09-11T12:56:22.803 回答
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));
  }
}

输出:

2012-09-02
2012-09-09
2012-09-16
2012-09-23
2012-09-30
于 2012-09-11T15:03:20.470 回答
3

与乔达

假设我们有一个约会:

DateTime date = new DateTime(2017, 6, 1, 0, 0, 0);

`首先我们需要知道该月是否有 31、30、28 或 29 天:

int lastofMonth = date.dayOfMonth().getMaximumValue();

从这里我们创建一个新的日期:

DateTime endOfMonth = new DateTime(2017, 6, lastOfMonth, 0, 0, 0);

我们找出最后一天是星期几:

int whatDayIsLast = endOfMonth.getDayOfWeek();

现在我们可以创建一个日期,它将是该月最后一个星期日的日期:

DateTime lastSunday = new DateTime(2017, 6, lastOfMonth - whatDayIsLast, 0, 0, 0);

对于我的示例(2017 年 6 月),结果将是:

DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd");
System.out.println(dtf.print(lastSunday);

2017-06-25

于 2018-02-17T06:44:23.783 回答
2
   static LocalDate getNthOfMonth(int n, int day_of_week, int month, int year)
   {
      if (n == -1)
      {
         return getNthOfMonth(0, day_of_week, month + 1, year);
      }
      final LocalDate compareDate = new LocalDate(year, month, 1);
      if (compareDate.getDayOfWeek() > day_of_week)
      {
         return compareDate.withDayOfWeek(day_of_week).plusDays(7 * n);   
      }
      else
      {
         return compareDate.withDayOfWeek(day_of_week).plusDays(7 * (n - 1));    
      }
   }  
于 2012-09-11T15:15:42.850 回答
2

// 以下方法将给出给定月份和年份的最后一个星期日

public Date getLastSunday(int month, int year) {
    Calendar cal = Calendar.getInstance();
    cal.set(year, month + 1, 1);
    int dayOftheWeek = cal.get(Calendar.DAY_OF_WEEK);
    int val = dayOftheWeek == Calendar.SUNDAY ? -7: -(dayOftheWeek-1);
    cal.add(Calendar.DAY_OF_MONTH, val);
    return cal.getTime();
}

// obj.getLastSunday(Calendar.OCTOBER, 2014);

于 2014-08-06T22:13:55.067 回答
2

使用 Java-8 java.timeAPI的解决方案

获取指定年份和月份最后一个星期日的本地日期:

为了使用Java的现代日期时间 APITemporalAdjusters.lastInMonth(DayOfWeek.SUNDAY)实现这一点,您可以将作为参数传递给任何LocalDate指定的年份和月份。

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.temporal.TemporalAdjusters;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(getLastSundayOfMonth(2020, 12));
    }

    public static LocalDate getLastSundayOfMonth(int year, int month) {
        return YearMonth.of(year, month)
                .atEndOfMonth() //Returns a LocalDate at the end of the month
                .with(TemporalAdjusters.lastInMonth(DayOfWeek.SUNDAY));
    }
}

输出:

2020-12-27

我曾经YearMonth#atEndOfMonth得到LocalDate. 代替这个,YearMonth#atDay也可以使用。

获取指定年份和月份的第 n 周(例如第 2 周四)的本地日期:

您可以TemporalAdjusters#dayOfWeekInMonth作为参数传递给任何LocalDate指定的年份和月份。

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.temporal.TemporalAdjusters;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(localDateOnNthDayOfWeekOfMonth(DayOfWeek.THURSDAY, 2, 2020, 12));
    }

    public static LocalDate localDateOnNthDayOfWeekOfMonth(DayOfWeek dayOfWeek, int ordinal, int year, int month) {
        return YearMonth.of(year, month)
                .atEndOfMonth() // Returns a LocalDate at the end of the month
                .with(TemporalAdjusters.dayOfWeekInMonth(ordinal, dayOfWeek));
    }
}

输出:

2020-12-10

从Trail: Date Time了解 Java-8 日期时间 API 。

Java 6 或 7 用户注意事项:

出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用ThreeTen-Backport,它将大部分java.time功能向后移植到 Java 6 和 7。如果您正在为 Android 项目工作并且您的 Android API 级别仍然不兼容 Java-8,请通过脱糖和How to use ThreeTenABP in Android Project检查可用的 Java 8+ API

于 2020-12-27T17:46:41.037 回答