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

kaibuki picture kaibuki · May 5, 2012 · Viewed 18k times · Source

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

Answer

ogniwo100 picture ogniwo100 · Oct 24, 2014

Hello to all coders :)

I work on little app to dive some data from database. To calculate previous weeks start and end date i use this code:

// Calendar object
Calendar cal = Calendar.getInstance();

// "move" cal to monday this week (i understand it this way)
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

// calculate monday week ago (moves cal 7 days back)
cal.add(Calendar.DATE, -7);
Date firstDateOfPreviousWeek = cal.getTime();

// calculate sunday last week (moves cal 6 days fwd)
cal.add(Calendar.DATE, 6);
Date lastDateOfPreviousWeek = cal.getTime();

Hope, that helps.