我是靠谱客的博主 迷路蓝天,这篇文章主要介绍java计算最后一个周日,获取Java中的最后一个星期五,现在分享给大家,希望可以做个参考。

I am working on a project where the requirement is to have a date calculated as being the last Friday of a given month. I think I have a solution that only uses standard Java, but I was wondering if anyone knew of anything more concise or efficient. Below is what I tested with for this year:

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());

}

解决方案

Based on marked23's suggestion:

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计算最后一个周日,获取Java中的最后一个星期五的全部内容,更多相关java计算最后一个周日,获取Java中内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(101)

评论列表共有 0 条评论

立即
投稿
返回
顶部