How can i calculate many week days in a month?

I'm trying to find out how many Mondays, for example, there are in a specific month of a specific year. Is there a library to import in java of a calendar of a specific year?

Upvotes: 0

Views: 521

Answers (3)

Pradnyarani
Pradnyarani

Reputation: 302

java.time

Using the java.time classes built into Java 8 and later.

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);

Upvotes: 2

Meno Hochschild
Meno Hochschild

Reputation: 44061

Even the old `Calendar´-API with all its disadvantages enables a solution:

    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

The new Java-8-API does not have a DAY_OF_WEEK_IN_MONTH-field (in strict sense), but you can do this:

    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

Upvotes: 0

Anton Dovzhenko
Anton Dovzhenko

Reputation: 2569

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;
    }
}

Upvotes: 0

Related Questions