简体   繁体   中英

Java Calendar using Calendar.DAY_OF_WEEK to get the first and the last dates for a particular date

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

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; eg, Sunday in US, Monday in France. **Parameters:** value - the given first day of the week.

Java Calender Doc

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());

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM