Joe
Joe

Reputation: 4532

How to generate N number of weeks from the date given - java

I am trying to create N of weeks from the date given and the week list should exclude the week which belongs to the week.

for example if i give todays date then i would like to generate the week excluding this week to N number of weeks.

below is the sample which serves my purpose but i am not able to create the N number of weeks also this piece of code prints the current week.

Calendar currentDate = Calendar.getInstance(Locale.US);
int firstDayOfWeek = currentDate.getFirstDayOfWeek();

Calendar startDate = Calendar.getInstance(Locale.US);
startDate.setTime(currentDate.getTime());

int days = (startDate.get(Calendar.DAY_OF_WEEK) + 7 - firstDayOfWeek) % 7;
startDate.add(Calendar.DATE, -days);

Calendar endDate = Calendar.getInstance(Locale.US);
endDate.setTime(startDate.getTime());
endDate.add(Calendar.DATE, 6);

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(df.format(startDate.getTime()) + " - " + df.format(endDate.getTime())); 

could some one help me on this?

Upvotes: 0

Views: 156

Answers (1)

Rajesh
Rajesh

Reputation: 2155

Print N number of weeks from the given date [excludes current week]:

public static void printNWeeks(Calendar startDate, int weeks) {

    int firstDayOfWeek = startDate.getFirstDayOfWeek();
    int days = (startDate.get(Calendar.DAY_OF_WEEK) + 7 - firstDayOfWeek) % 7;
    startDate.add(Calendar.DATE, -days);

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

    for (int i = 1; i <= weeks; i++) {

        startDate.add(Calendar.DATE, 7); // change to 7 to -7 for back dates

        Calendar endDate = Calendar.getInstance(Locale.US);
        endDate.setTime(startDate.getTime());
        endDate.add(Calendar.DATE, 6);          

        System.out.println(df.format(startDate.getTime()) + " - "
                + df.format(endDate.getTime()));
    }
}

Sample Invocations:

public static void main(String[] args) {        

   //From the given date
    Calendar startDate = Calendar.getInstance(Locale.US);
    startDate.set(2015, Calendar.JANUARY, 30);
    printNWeeks(startDate, 5);

    //From Current Date     
    startDate = Calendar.getInstance(Locale.US);
    printNWeeks(startDate, 5);
}

Upvotes: 1

Related Questions