java一个月的最后一个星期日 [英] java last sunday of a month

查看:96
本文介绍了java一个月的最后一个星期日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取任何给定月份的最后一个星期日,但是如果星期日是下个月的第一天,它会显示某个日期,而不是同一个月的上周,所以它在某些输入上起作用.

I want to get the last sunday of any given month, and its working to a point however on some inputs if the sunday is the first day of next month it shows that date instead of the same month's last week. Here is what

public static String getLastSunday(int month, int year) {
    Calendar cal = Calendar.getInstance();
    cal.set(year, month, 1);
    if (leap(year)) {
        cal.add(Calendar.DAY_OF_MONTH, -(cal.get(Calendar.DAY_OF_WEEK) - 2));
    } else {
        cal.add(Calendar.DAY_OF_MONTH, -(cal.get(Calendar.DAY_OF_WEEK)%7 - 1));
    }
    return cal.getTime().toString().substring(0, 10);
}

将函数调用为:

getLastSunday(10, 2015);

返回输出:

Sun Nov 01

我哪里出错了?另外,如果是the年,我不确定从-1到-2是否正确,我对此进行了研究,但找不到有用的东西.

Where did I go wrong? Also if it is the leap year, I am not sure if going from -1 to -2 is correct, I researched about it but couldnt find anything useful.

推荐答案

尝试这种方式

public static Date getLastSunday( int month, int year ) {
       Calendar cal = Calendar.getInstance();
       cal.set( year, month + 1, 1 );
       cal.add(Calendar.DATE, -1); 
   cal.add( Calendar.DAY_OF_MONTH, -( cal.get( Calendar.DAY_OF_WEEK ) - 1 ) );
       return cal.getTime();
    }

来源

这篇关于java一个月的最后一个星期日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆