我如何计算一个月内的许多工作日?

时间:2017-01-04 05:43:28

标签: java import calendar

我试图找出有多少个星期一,例如,特定年份的特定月份。 是否有一个库可以在特定年份的日历中导入java?

3 个答案:

答案 0 :(得分:2)

java.time

使用Java 8及更高版本中内置的java.time类。

YearMonth month = YearMonth.of(2017, 1);
LocalDate start = month.atDay(1).with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY));

int count = (int) ChronoUnit.WEEKS.between(start, month.atEndOfMonth()) + 1;

System.out.println(count);

答案 1 :(得分:0)

Java 7 + JodaTime

import org.joda.time.DateTimeConstants;
import org.joda.time.Days;
import org.joda.time.LocalDate;

import java.util.Date;

public class Test {

    public static int getNumberOfMondays(Date start, Date end) {
        LocalDate startDate = LocalDate.fromDateFields(start);
        LocalDate endDate = LocalDate.fromDateFields(end);
        int days = Days.daysBetween(startDate, endDate).getDays();
        int mondayCount = 0;
        //Get number of full weeks: 1 week = 1 Monday
        mondayCount += days / 7;
        int remainder = days % 7;
        if (startDate.dayOfWeek().get() == DateTimeConstants.MONDAY || startDate.dayOfWeek().get() > (startDate.dayOfWeek().get() + remainder) % 8) {
            mondayCount++;
        }
        return mondayCount;
    }
}

答案 2 :(得分:0)

即使是具有所有缺点的旧`Calendar'-API也能实现解决方案:

    int year = 2017;
    int month = Calendar.JANUARY;
    int dow = Calendar.MONDAY;

    GregorianCalendar gcal = new GregorianCalendar(year, month, 1);
    while (gcal.get(Calendar.DAY_OF_WEEK) != dow) {
        gcal.add(Calendar.DAY_OF_MONTH, 1);
    }
    System.out.println(gcal.getActualMaximum(Calendar.DAY_OF_WEEK_IN_MONTH)); // 5

新的Java-8-API没有DAY_OF_WEEK_IN_MONTH字段(严格意义上),但您可以这样做:

    int year = 2017;
    int month = 1;

    LocalDate ld1 =
      LocalDate.of(year, month, 1).with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));
    LocalDate ld2 =
      LocalDate.of(year, month, 1).with(TemporalAdjusters.lastInMonth(DayOfWeek.MONDAY));
    System.out.println(ChronoUnit.WEEKS.between(ld1, ld2) + 1); // 5