Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all days of a current week?

Tags:

java

I need to get numbers of all days of a week (MON to SUN) based on which day is sent as a parameter.

For example,
I pass May 2 and I get an array [30,1,2,3,4,5,6] which is this week actually.
Or, I pass May 16 and I get an array [14,15,16,17,18,19,20].

I tried to use this code, but it return 7 days from today, which I do not want.

        //get which week of month
        Calendar now = Calendar.getInstance();
        now.set(mYear, mMonth, Integer.parseInt(extractedDay));
        int weekOfMonth = now.get(Calendar.WEEK_OF_MONTH);

        //get all days of clicked week
        SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.set(mYear, mMonth, Integer.parseInt(extractedDay));

        String[] days = new String[7];
        for (int i = 0; i < 7; i++)
        {
            days[i] = format.format(calendar.getTime());
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

But this is not what I need. I need to pass today's day (THU) and to get dates of this week of May - Mon, Apr 30 to Sun, May 6.

EDIT

I realized that I have a code which detects which week of a month it is. Is there a way to use this data and to set a date for Monday? For example, I pass May 16 and then I detect that it's 3rd week of May, and the I set the variable firstDayOfWeek (a new variable) to May 14.

like image 751
sandalone Avatar asked May 03 '12 10:05

sandalone


1 Answers

You have first to subtract the weekday of the day you choose, in order to start from the first day of week. Try the following code:

public static void main(String[] args){
    Calendar now = Calendar.getInstance();

    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");

    String[] days = new String[7];
    int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 2; //add 2 if your week start on monday
    now.add(Calendar.DAY_OF_MONTH, delta );
    for (int i = 0; i < 7; i++)
    {
        days[i] = format.format(now.getTime());
        now.add(Calendar.DAY_OF_MONTH, 1);
    }
    System.out.println(Arrays.toString(days));

}

Today, it output:

[04/30/2012, 05/01/2012, 05/02/2012, 05/03/2012, 05/04/2012, 05/05/2012, 05/06/2012]

like image 163
Andrea Parodi Avatar answered Nov 15 '22 22:11

Andrea Parodi