Get Last Friday of Month in Java

后端 未结 16 1937
一生所求
一生所求 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:58

    Below program is for the last Friday of each month. it can be used to get the last of any day of the week in any month. The variable offset=0 means current month(system date), offset=1 means next month, so on. The getLastFridayofMonth(int offset) method will return the last Friday.

    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    
    public class LastFriday {
    
      public static Calendar getLastFriday(Calendar cal,int offset){
        int dayofweek;//1-Sunday,2-Monday so on....
        cal.set(Calendar.MONTH,cal.get(Calendar.MONTH)+offset);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); //set calendar to last day of month
        dayofweek=cal.get(Calendar.DAY_OF_WEEK); //get the day of the week for last day of month set above,1-sunday,2-monday etc
        if(dayofweek

提交回复
热议问题