Which weeks are associated with which months?

java, jodatime

Solution

You have to instantiate `DateTime` object for specified week number, and then just reads its month property (using Joda-Time and Google Guava).

        DateTime dateTime = new DateTime().withWeekOfWeekyear(i).withDayOfWeek(DateTimeConstants.MONDAY);
        if (dateTime.dayOfMonth().getMaximumValue() - dateTime.dayOfMonth().get() < 3) {
            dateTime = dateTime.plusMonths(1);
        }
        int month = dateTime.monthOfYear().get();

We can also use below function to print all months with belonging to them weeks:

public static void main(String[] args) {
    Multimap<Integer, Integer> monthsWithWeeks = LinkedListMultimap.create();

    int weeksInYear = new DateTime().withYear(2014).weekOfWeekyear().getMaximumValue();
    for (int i = 1; i <= weeksInYear; i++) {
        DateTime weekDate = new DateTime().withWeekOfWeekyear(i).withDayOfWeek(DateTimeConstants.MONDAY);
        if (weekDate.dayOfMonth().getMaximumValue() - weekDate.dayOfMonth().get() < 3) {
            weekDate = weekDate.plusMonths(1);
        }
        int month = weekDate.monthOfYear().get();
        monthsWithWeeks.put(month, i);
    }

    for (Integer month : monthsWithWeeks.keySet()) {
        System.out.println(String.format("%d => [%s]", month, Joiner.on(',').join(monthsWithWeeks.get(month))));
    }
}

Problem

Is there a way in JodaTime to easily determine which weeks belong to which month? Something that given a month number returns the weeks of year associated with it. A week should be linked with a specific month if 4+ of its days fall within it. ``` In 2014 for month = 1 then weeks = [1, 2, 3, 4, 5] (note 5 weeks because of 4 days rule) In 2014 for month = 3 then weeks = [10, 11, 12, 13] (note 4 weeks because of same rule) ``` I don't want to calculate this 'manually'...

Original source