4

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

calling the function as:

getLastSunday(10, 2015);

returns the output:

Sun Nov 01

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.

mrahmat
  • 617
  • 6
  • 21

3 Answers3

4

tl;dr

YearMonth.of( 2015 , Month.NOVEMBER )                              // Represent the entirety of a specified month.
    .atEndOfMonth()                                                // Get the date of the last day of that month.
    .with( TemporalAdjusters.previousOrSame( DayOfWeek.SUNDAY ) )  // Move to the previous Sunday, or keep if already Sunday.

Avoid legacy date-time classes

The Question and other Answers are outmoded, using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

Use smart objects, not dumb primitives

Rather than pass year and month as mere integers, pass a single argument of YearMonth class. Doing so ensures valid values, makes your code more self-documenting, and provides type-safety.

YearMonth ym = YearMonth.of( 2015 , Month.NOVEMBER ) ;  // Or YearMonth.of( 2015 , 11 ) with sane numbering for month 1-12 for January-December.

The LocalDate class represents a date-only value without time-of-day and without time zone.

Get the last day of the month.

LocalDate endOfMonth = ym.atEndOfMonth() ;

Find the previous Sunday, or keep the end-of-month if it is already a Sunday. Use a TemporalAdjuster found in the TemporalAdjusters class.

LocalDate lastSundayOfPriorMonth = endOfMonth.with( TemporalAdjusters.previousOrSame( DayOfWeek.SUNDAY ) ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
3

try this way

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

source

Community
  • 1
  • 1
SpringLearner
  • 13,738
  • 20
  • 78
  • 116
2

Try this out (Remember Month value is 0-based. e.g., 0 for January)

Calendar cal = Calendar.getInstance();
cal.set(year, month, 1);
cal.add(Calendar.MONTH, 1);  
cal.set(Calendar.DAY_OF_MONTH, 1);  
cal.add(Calendar.DATE, -1);  

cal.add(Calendar.DATE, -(cal.get(Calendar.DAY_OF_WEEK) -1));
return cal.getTime().toString().substring(0, 10);

So if you want to call this method for Oct 2015, then call like this:

getLastSunday(9, 2015);

Its doing the following things: 1. Setting the passed year and monthe to the calendar object getLastSunday(9, 2015); 2. Then updates the calendar object to the last day of the current month by using this code:

cal.add(Calendar.MONTH, 1);  
cal.set(Calendar.DAY_OF_MONTH, 1);  
cal.add(Calendar.DATE, -1);
  1. Then subtracts the number of days from the current date tot the last sunday: JAVA sets 1 for SUNDAY , 2 for MONDAY and so on. So, if the last day is MONDAY i.e. 2 then it will subtract 1 from it to get the last sunday of the month.

Hope it helps.

avin
  • 459
  • 5
  • 14