Rahul
Rahul

Reputation: 1667

How to print all day of week in android

I want to display all day of a week on click of an button. The action will be like this, For example suppose the month is FEB - 2013, So on click of button for the first time i want to display this days.

3/11/2013, 4/11/2013, 5/11/2013, 6/11/2013, 7/11/2013, 8/11/2013, 9/11/2013

on click of button for the second time i want to display like this

10/11/2013, 11/11/2013, 12/11/2013, 13/11/2013, 14/11/2013, 15/11/2013, 16/11/2013

Similarly on each click of button i want to display rest of the days in this format. So how that can be done, i have tried this code but it will display

3/11/2013, 4/11/2013, 5/11/2013, 6/11/2013, 7/11/2013, 8/11/2013, 9/11/2013 

code i used

Calendar c = Calendar.getInstance();

// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);

// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
for (int i = 0; i < 7; i++) 
{
    System.out.println(df.format(c.getTime()));
    c.add(Calendar.DAY_OF_MONTH, 1);
}

Upvotes: 0

Views: 1514

Answers (2)

Jayamohan
Jayamohan

Reputation: 12924

Yours were almost there, Just added c.add(Calendar.WEEK_OF_YEAR, week); to increment the week based on the input parameter

public static void getDaysOfWeek(int week) {
    Calendar c = Calendar.getInstance();
    // Set the calendar to monday of the current week
    c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    c.add(Calendar.DATE, week * 7);
    // Print dates of the current week starting on Monday
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
    for (int i = 0; i < 7; i++) {
        System.out.println(df.format(c.getTime()));
        c.add(Calendar.DAY_OF_MONTH, 1);
    }
}

Use the above method to get the days of the week. Just pass 0 for the first time to the method, 1 for the next click and so on. You will get the corresponding days of the week.

Upvotes: 1

Achintya Jha
Achintya Jha

Reputation: 12843

public static void main(String[] args) {
    int next = 1;
    for(int i =0 ;i< 4 ;i++)
    weekOfGivenMonth(next++);
}

private static void weekOfGivenMonth(int weekNext) {

    Calendar c = Calendar.getInstance();

    c.set(Calendar.WEEK_OF_MONTH, weekNext);

    DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
    for (int i = 0; i < 7; i++) {
        System.out.println(df.format(c.getTime()));
        c.add(Calendar.DATE, 1);
    }

}

Try this I edited as your requirement. I used loop instead of that you should use button to call second , third and fourth week of the month.

Upvotes: 0

Related Questions