Android Calendar: Changing the start day of week

25,028

Solution 1

Calendar days have values 1-7 for days Sunday-Saturday. getFirstDayOfWeek returns one of this values (usually of Monday or Sunday) depending on used Locale. Calendar.getInstance uses default Locale depening on phone's settings, which in your case has Monday as first day of the week.

One solution would be to use other Locale:

Calendar.getInstance(Locale.US).getFirstDayOfWeek()

would return 1, which is value of Calendar.SUNDAY

Other solution would be to use chosen day of week value like

cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);

Problem is, Calendar is using its inner first day of the week value in set as well. Example:

Calendar mondayFirst = Calendar.getInstance(Locale.GERMANY); //Locale that has Monday as first day of week
mondayFirst.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
log(DateUtils.formatDateTime(context, mondayFirst.getTimeInMillis(), 0));
//prints "May 19" when runned on May 13

Calendar sundayFirst = Calendar.getInstance(Locale.US); //Locale that has Sunday as first day of week
sundayFirst.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
log(DateUtils.formatDateTime(context, sundayFirst.getTimeInMillis(), 0));
//prints "May 12" when runned on May 13

If you don't want to use Locale or you need other day as the first day of the week, it may be best to calculate start of the week on your own.

Solution 2

GregorianCalendar cal = new GregorianCalendar(yy, currentMonth, 0);

changing the value 0 - starts day from monday changing the value 1 - starts day from sunday and so on..

hope this helps and works :)

Share:
25,028
Mouhamad Lamaa
Author by

Mouhamad Lamaa

Updated on July 09, 2022

Comments

  • Mouhamad Lamaa
    Mouhamad Lamaa almost 2 years

    i have a little problem, i'm developing an application, and i need to change the start day of the week from monday to another one (thursday, of saturday). is this possible in android, i need to calculate the start to week and its end knowing the date. (the week starts ano thursday as example)

    Note: i'm just a beginner in android development. here is my code SimpleDateFormat dateformate = new SimpleDateFormat("dd/MM");

    // get today and clear time of day
    Calendar cal = Calendar.getInstance();
    
    // get start of this week in milliseconds
    cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
    cal.add(Calendar.DAY_OF_YEAR, 7*(WeekIndex-1));
    result = dateformate.format(cal.getTime());
    
    cal.add(Calendar.DAY_OF_YEAR, 6 );
    
    result=result+" - " + dateformate.format(cal.getTime());
    

    using the above code im getting the result but with monday as the star of week.

    Note: i can't add day to the result because week index changes with the changing of it's start

  • Samadhan Medge
    Samadhan Medge over 6 years
    Working fine, Thanks +1