Search code examples
javaandroidcalendargregorian-calendar

Using GregorianCalendar to get weeks


I'm looking to utilize GregorianCalendar to do some logic based on days. Is there any way to see if 2 dates are in the same week? I've tried using get(Calendar.WEEK_OF_YEAR), and this has the two downsides of:

1) Starting on the wrong day of the week (which seems to have a potential solution in setFirstDayOfWeek, however preliminary testing has not been successful.
2) This solution does not carry over years nicely. For example - Dec 30th, 2014 and Jan 1, 2015 should be in the same week.

Is there any solution to this that doesn't require switching libraries?


Solution

  • OK, since you've stated there will be a time component, I'd use something similar to @MadProgrammer's answer, but without the complexity of using an entire date range. I'd have a static method something like this.

    public static Date firstOfWeek(Calendar cal) {
        Calendar copy = new GregorianCalendar( 
            cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
        copy.set(Calendar.DAY_OF_WEEK, copy.getFirstDayOfWeek());
        return copy.getTime();
    }
    

    This returns a Date for the first day of the week that includes a particular Calendar. You can then check whether two calendars fall in the same week like this.

    if (firstOfWeek(cal1).equals(firstOfWeek(cal2))) {
        ...
    }