Get all Fridays in a date Range in Java

后端 未结 7 665
梦如初夏
梦如初夏 2020-12-16 15:48

I recently came across a task where i have to get all Fridays in a date range. I wrote a small piece of code and was surprised see some strange behaviour.

Below is m

相关标签:
7条回答
  • 2020-12-16 16:20
    public static List<Date> getWeekNumberList(Date currentMonthDate) {
        List<Date> dates = new ArrayList<>(10);
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTime(currentMonthDate);
        startCalendar.set(Calendar.DAY_OF_MONTH,
                startCalendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(currentMonthDate);
        endCalendar.set(Calendar.DAY_OF_MONTH,
                endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH));
    
        Date enddate = endCalendar.getTime();
        while (startCalendar.getTime().before(enddate)) {
            if (startCalendar.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
                Date result = startCalendar.getTime();
                dates.add(result);
                startCalendar.add(Calendar.WEEK_OF_MONTH, 1);
            } else {
    
                startCalendar.add(Calendar.DAY_OF_MONTH, 1);
            }
        }
        return dates;
    }
    
    0 讨论(0)
提交回复
热议问题