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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值