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

前端 未结 3 1990
不知归路
不知归路 2021-01-28 19:49

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 check

相关标签:
3条回答
  • 2021-01-28 19:56

    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.

    0 讨论(0)
  • 2021-01-28 20:02

    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.
    

    Java Calender Doc

    0 讨论(0)
  • 2021-01-28 20:13

    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());
    
    0 讨论(0)
提交回复
热议问题