在普通的
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)
解决方法
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 year) { LocalDate date = new LocalDate(year,1).dayOfMonth() .withMaximumValue() .dayOfWeek() .setCopy(day_of_week); if(date.getMonthOfYear() != month) { return date.dayOfWeek().addToCopy(-7); } return date; } }