Reputation: 4103
In my application there lies a code which works abruptly sometimes, its about getting a week interval using the java calendar object through Calendar.DAY_OF_WEEK. The code checked for monday as start of week and sunday as end of week like: fromCal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); toCal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); the toCal is set as the last sunday instead of coming sunday. Is there any alternate way to do this other then this kind of hard coding.
Appriciate the help in advance.
Thanks,
Vaibhav
Upvotes: 0
Views: 6615
Reputation: 55957
Be very clear on your desired behaviour here. You start with a calendar object whose "now" is some day of the week, perhaps "today". You the call set(DAY_OF_WEEK, ...). What effect do you desire if the Calendar's today is Tuesday? Sunday? Monday?
As observed in other answers, what happens depends upon the Calendar's opinion about what the First day of week is. So first set that to your chosen value. You will then (according to this answer get a Sunday and a Monday in the current week, which may not be what you want - what exactly do you need if today is Sunday? - some systems might actually be "thinking" about the next week.
Personally I might get my Monday according to some business rules and the get the Sunday after by adding 6 days.
Upvotes: 1
Reputation: 2907
The issue is in locale. In English(US), Sunday is the first day of the week. Check this code:
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("FirstDayOfWeek="+cal.getFirstDayOfWeek());
System.out.println(cal.getTime().toString());
cal = Calendar.getInstance(Locale.FRANCE);
System.out.println("FirstDayOfWeek="+cal.getFirstDayOfWeek());
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println(cal.getTime().toString());
Upvotes: 2
Reputation: 43299
I guess you have to set the start of week to monday, otherwise last sunday IS the sunday of the week.
setFirstDayOfWeek
public void setFirstDayOfWeek(int value)
Sets what the first day of the week is; e.g., Sunday in US, Monday in France. **Parameters:** value - the given first day of the week.
Upvotes: 2