使用Java获取本月的最后一个星期五
我正在一个项目中,要求将日期计算为给定月份的最后一个星期五。我认为我有一个仅使用标准Java的解决方案,但我想知道是否有人知道更简洁或更有效的方法。以下是我今年测试的内容:
for (int month = 0; month < 13; month++) { GregorianCalendar d = new GregorianCalendar();
d.set(d.MONTH, month);
System.out.println("Last Week of Month in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + d.getLeastMaximum(d.WEEK_OF_MONTH));
d.set(d.DAY_OF_WEEK, d.FRIDAY);
d.set(d.WEEK_OF_MONTH, d.getActualMaximum(d.WEEK_OF_MONTH));
while (d.get(d.MONTH) > month || d.get(d.MONTH) < month) {
d.add(d.WEEK_OF_MONTH, -1);
}
Date dt = d.getTime();
System.out.println("Last Friday of Last Week in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + dt.toString());
}
回答:
根据marked23的建议:
public Date getLastFriday( int month, int year ) { Calendar cal = Calendar.getInstance();
cal.set( year, month + 1, 1 );
cal.add( Calendar.DAY_OF_MONTH, -( cal.get( Calendar.DAY_OF_WEEK ) % 7 + 1 ) );
return cal.getTime();
}
以上是 使用Java获取本月的最后一个星期五 的全部内容, 来源链接: utcz.com/qa/431066.html