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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With