Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which weeks are associated with which months?

Tags:

java

jodatime

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'...

like image 471
Marsellus Wallace Avatar asked Jan 10 '14 21:01

Marsellus Wallace


People also ask

What are the weeks for each month of pregnancy?

The average calendar month is 4-5 weeks, but a pregnancy month is always exactly 4 weeks. If you're 32 weeks pregnant, you would say you're 8 months pregnant even if some of the calendar months were closer to 5 weeks long.

What weeks are 7 months pregnant?

Your 3rd trimester starts during your 7th month of pregnancy, on week 28.

Which week is considered as 6 months?

It turns out that six months pregnant could start at week 21, 22, or 23 and extend through week 24 to week 27 or 28.

At what week does month 4 start?

At 16 weeks, you're officially 4 months pregnant!


1 Answers

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))));
    }
}
like image 94
Jakub Kubrynski Avatar answered Oct 03 '22 18:10

Jakub Kubrynski