Java last Sunday of the month

I want to get the last Sunday of a month, and his work on the point, however, at some entries, if Sunday is the first day of the next month, it shows this date instead of the same month last week. That's 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);
}

calls the function as:

getLastSunday(10, 2015);

returns the result:

Sun Nov 01

Where am I wrong? Also, if it's a leap year, I'm not sure if it goes from -1 to -2 correctly, I researched it, but found nothing useful.

+4
source share
3 answers

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

+2
source

Try this (Remember Month value is 0, for example, 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);

: 1.   getLastSunday (9, 2015); 2. :

cal.add(Calendar.MONTH, 1);  
cal.set(Calendar.DAY_OF_MONTH, 1);  
cal.add(Calendar.DATE, -1);
  1. : JAVA 1 , 2 . , - , .. 2, 1 , .

, .

+1

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.

, , , java.time.

,

, YearMonth. , .

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

LocalDate .

.

LocalDate endOfMonth = ym.atEndOfMonth() ;

, . TemporalAdjuster, TemporalAdjusters.

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

java.time

java.time Java 8 . legacy , java.util.Date, Calendar SimpleDateFormat.

Joda-Time, , java.time.

, . Oracle. Qaru . JSR 310.

java.time?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proof of possible future additions to java.time. Here you can find useful classes, such as Interval, YearWeek, YearQuarterand longer .

0
source

All Articles