Search code examples
javadatecalendardayofweek

Get next week and previous week staring and ending dates in java


I want to get the starting and ending dates of a week for example

2012-05-06 to 2012-05-12
2012-05-13 to 2012-05-19

The code I have written is

currWeekCalender.add(Calendar.WEEK_OF_YEAR, 1);

    String dateStart =  currWeekCalender.get(Calendar.YEAR) + "-" + addZero((currWeekCalender.get(Calendar.MONTH) + 1)) + "-" + addZero(currWeekCalender.getFirstDayOfWeek());
    currWeekCalender.add(Calendar.DAY_OF_MONTH,7);
    String dateEnd =  currWeekCalender.get(Calendar.YEAR) + "-" + addZero((currWeekCalender.get(Calendar.MONTH) + 1)) + "-" + addZero(currWeekCalender.get(Calendar.DAY_OF_MONTH));

but the results are not correct, also I want previous weeks date.

Thanks


Solution

  • Your problem is that getFirstDayOfWeek() returns the first day of the week; e.g., Sunday in US, Monday in France. It does not return a day of the month. See javadoc.

    The first day in a month that is the start of the week is (in pseudo-code)

    ((7 + (firstDayOfWeek - dayOfWeek(firstOfMonth))) % 7) + 1
    

    You can translate that into java.util.Calendar code if you like, but I would suggest using Joda time instead.


    also I want previous weeks date.

    Just subtract seven days maybe using add

    currCalendar.add(Calendar.DAY_OF_MONTH, -7)
    

    This may involve underflow, but add deals with that.

    add(f, delta)

    adds delta to field f. This is equivalent to calling set(f, get(f) + delta) with two adjustments:

    Add rule 1. The value of field f after the call minus the value of field f before the call is delta, modulo any overflow that has occurred in field f. Overflow occurs when a field value exceeds its range and, as a result, the next larger field is incremented or decremented and the field value is adjusted back into its range.