Javaの - 時間の間隔で月の出現の日を数えます

user666:

私は、Java 8を使用しています、私は、インデックス= Xを持つ区間では、我々が持っているどのように多くの日数カウントする必要があります。例:31-1-2019まで2019年1月1日から、我々は1日目の1が発生しています。

30 30 + 31 + 28:月の最後の日は、私はそれらをすべて一例を数えるにしたい場合は、私は数日の範囲、日Xのちょうど数をしたくありません

user666:
    public long getNumberOfDayOfMonthBetweenDates(LocalDate startDate, LocalDate endDate, int dayOfMonth) {
    long result = -1;
    if (startDate != null && endDate != null && dayOfMonth > 0 && dayOfMonth < 32) {
        result = 0;
        LocalDate startDay = getDayInCurrentMonth(startDate, dayOfMonth);
        // add one day as end date is exclusive
        // add + 1 to cover higher possibilities (month and a half or half month or so)
        long totalMonths = ChronoUnit.MONTHS.between(startDate, endDate.plusDays(1)) + 2;
        for (int i = 0; i < totalMonths; i++) {
            if ((!startDay.isBefore(startDate) && startDay.isBefore(endDate)) || startDay.equals(startDate) || startDay.equals(endDate)) {
                result++;
            }
            startDay = getDayInCurrentMonth(startDay.plusMonths(1), dayOfMonth);
        }
    }
    return result;
}

private LocalDate getDayInCurrentMonth(LocalDate startDate, int dayOfMonth) {
    LocalDate dayOfThisMonth;
    try {
        dayOfThisMonth = startDate.withDayOfMonth(dayOfMonth);
    } catch (DateTimeException e) {
        // handle cases where current month does not contain the given day (example 30 in Feb)
        dayOfThisMonth = startDate.withDayOfMonth(startDate.lengthOfMonth());
    }
    return dayOfThisMonth;
}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=209437&siteId=1