Skip to content Skip to sidebar Skip to footer

Android Calendar: Changing The Start Day Of Week

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 andro

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:

GregorianCalendarcal=newGregorianCalendar(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 :)

Solution 3:

publicintgetWeekdayOfMonth(int year, int month){
    Calendar cal = Calendar.getInstance();
    cal.set(year, month-1, 1);
    dayOfWeek = cal.get(Calendar.DAY_OF_WEEK)-1;
    return dayOfWeek;
}

weekday = getWeekdayOfMonth();

intday= (weekday - firstweek) <0 ? (7- (firstweek - weekday)) : (weekday - firstweek);

"firstweek" means what the start day of you want

then you can calculate the first day you should show.If you have simple method,please tell us. thks

Solution 4:

Problem in my case was using Calendar instance returned by MaterialDialogDatePicker, which although having the same Locale as my Calendar.getInstance(Locale...), was having different Calendar.firstDayOfWeek. If you're experiencing the same issue, my workaround was to create new instance of Calendar with my Locale and just changing the property time to the one returned by the DatePicker as following:

val correctCal = Calendar.getInstance(Locale...)?.apply {
        time = datePickerCal.time
}

This should return proper Calendar.firstDayOfWeek based on your Locale.

Post a Comment for "Android Calendar: Changing The Start Day Of Week"