Receive dates and dates in java next week and previous week

I want to get the start and end dates of the week for example

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

The code I wrote 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 incorrect, also I want the dates of previous weeks.

thank

+3
source share
4 answers

Your problem is that it getFirstDayOfWeek()returns the first day of the week; for example, Sunday in the USA, Monday in France. It does not return the day of the month. See javadoc .

The first day of the month that begins at the beginning of the week (in pseudo-code)

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

You can translate this into code java.util.Calendarif you want, but I would suggest using Joda's time.


.

, , add

currCalendar.add(Calendar.DAY_OF_MONTH, -7)

, add .

add(f, delta)

delta f. set(f, get(f) + delta) :

1. f f delta, , f. , , , .

+2

Hello to all the codes :)

I am working on a small application to plunge some data from a database. To calculate the start and end dates of previous weeks, 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 this helps.

+2
source

Java version 8

Print previous 10 weeks

final ZonedDateTime input = ZonedDateTime.now();

for(int i = 1; i < 10; i++) {
    final ZonedDateTime startOfLastWeek = input.minusWeeks(i).with(DayOfWeek.MONDAY);
    System.out.print(startOfLastWeek.format(DateTimeFormatter.ISO_LOCAL_DATE));
    final ZonedDateTime endOfLastWeek = startOfLastWeek.plusDays(6);
    System.out.println(" - " + endOfLastWeek.format(DateTimeFormatter.ISO_LOCAL_DATE));
}
+1
source

All Articles