java last sunday of a month [duplicate]

风流意气都作罢 提交于 2021-02-09 03:57:33

问题


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.


回答1:


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:


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.




回答3:


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?

  • Java SE 8, Java SE 9, and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

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.



来源:https://stackoverflow.com/questions/29026602/java-last-sunday-of-a-month

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!