Get Last Friday of Month in Java

后端 未结 16 1956
一生所求
一生所求 2020-11-28 11:28

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 Ja

16条回答
  •  死守一世寂寞
    2020-11-28 11:48

    Hope this helps..

    public static void getSundaysInThisMonth(int monthNumber, int yearNumber){
        //int year =2009;
        //int dayOfWeek = Calendar.SUNDAY;
        // instantiate Calender and set to first Sunday of 2009
        Calendar cal = new GregorianCalendar();
        cal.set(Calendar.MONTH, monthNumber-1);
        cal.set(Calendar.YEAR, yearNumber);
        cal.set(Calendar.DATE, 1);
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        int dateOfWeek = cal.get(Calendar.DATE);
        while (dayOfWeek  != Calendar.SUNDAY) {
           cal.set(Calendar.DATE, ++dateOfWeek);
           dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
          }
        cal.set(Calendar.DATE, dateOfWeek);
    
        int i = 1;
        while (cal.get(Calendar.YEAR) == yearNumber && cal.get(Calendar.MONTH)==monthNumber-1)
        {
                System.out.println("Sunday " + " " + i + ": " + cal.get(Calendar.DAY_OF_MONTH));
                cal.add(Calendar.DAY_OF_MONTH, 7);
                i++;
        }
    
      }
      public static void main(String args[]){
        getSundaysInThisMonth(1,2009);
      }
    

提交回复
热议问题