Get Last Friday of Month in Java

后端 未结 16 1834
一生所求
一生所求 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 12:04

    Slightly easier to read, brute-force approach:

    public int getLastFriday(int month, int year) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month, 1, 0, 0, 0); // set to first day of the month
        cal.set(Calendar.MILLISECOND, 0);
    
        int friday = -1;
        while (cal.get(Calendar.MONTH) == month) { 
            if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) { // is it a friday?
                friday = cal.get(Calendar.DAY_OF_MONTH);
                cal.add(Calendar.DAY_OF_MONTH, 7); // skip 7 days
            } else {
                cal.add(Calendar.DAY_OF_MONTH, 1); // skip 1 day
            }
        }
        return friday;
    }
    
    0 讨论(0)
  • 2020-11-28 12:06

    I would use a library like Jodatime. It has a very useful API and it uses normal month numbers. And best of all, it is thread safe.

    I think that you can have a solution with (but possibly not the shortest, but certainly more readable):

    DateTime now = new DateTime();      
    DateTime dt = now.dayOfMonth().withMaximumValue().withDayOfWeek(DateTimeConstants.FRIDAY);
    if (dt.getMonthOfYear() != now.getMonthOfYear()) {
      dt = dt.minusDays(7);
    }       
    System.out.println(dt);
    
    0 讨论(0)
  • 2020-11-28 12:07

    here's how to get the last friday, or whatever week day, of the month:

    Calendar thisMonth = Calendar.getInstance();
    dayOfWeek = Calendar.FRIDAY; // or whatever
    thisMonth.set(Calendar.WEEK_OF_MONTH, thisMonth.getActualMaximum(Calendar.WEEK_OF_MONTH);;
    thisMonth.set(Calendar.DAY_OF_WEEK, dayOfWeek);
    int lastDay = thisMonth.get(Calendar.DAY_OF_MONTH); // this should be it.
    
    0 讨论(0)
  • 2020-11-28 12:07
    public static Calendar getNthDow(int month, int year, int dayOfWeek, int n) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month, 1);
        cal.set(Calendar.DAY_OF_WEEK, dayOfWeek);
        cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, n);
        return (cal.get(Calendar.MONTH) == month) && (cal.get(Calendar.YEAR) == year) ? cal : null;
    }
    
    0 讨论(0)
提交回复
热议问题