Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I construct a Locale with a custom first day of week?

I need to have a Locale object that's exactly the same as another but with a different first day of week (i.e.: Sunday instead of Saturday).

Specifically, I need an Arabic-Egypt locale that starts on Sunday. I'm using a calendar control that only supports changing its locale, hence my requirement.

like image 371
mido Avatar asked Jul 12 '15 13:07

mido


2 Answers

Locale objects don't control the first day of week. This is done by the Calendar class in the following way:

Locale locale = Locale.forLanguageTag("ar-EG");
Calendar calendar = Calendar.getInstance(locale);
calendar.setFirstDayOfWeek(Calendar.SUNDAY);

According to your comment on Gautam Jose's answer:

Normally this would've been just fine. Thing is, the control I'm using keeps instantiating Calendar objects according to the default locale (application scope wise), so a custom locale. I actually tried reverse engineering the control and it does not provide leeway around the issue due to it using private members (i.e.: inheriting it can't help here)

You won't need to inherit if you change these private members directly using Java reflection API.

First, inspect the control's class to find the Calendar field:

public class CalendarControl {
    private Calendar calendar;
}

Now use:

CalendarControl control; // The instance to manipulate
try {
    Field field = control.getClass().getDeclaredField("calendar");
    field.setAccessible(true);
    field.set(control, calendar); // Pass the new object we created at top of this answer
} catch (Exception ex) {
    // You must catch NoSuchFieldException and IllegalAccessException here
}
like image 52
Atom 12 Avatar answered Nov 12 '22 20:11

Atom 12


You can create a Calendar object and set first day using calender.setFirstDayOfWeek() method.

Locale locale = new Locale("ar-EG", "EG");
TimeZone timeZone = TimeZone.getTimeZone("Egypt");
Calendar calendar = GregorianCalendar.getInstance(locale);
Calendar calendar2 = GregorianCalendar.getInstance(locale);
calendar2.setFirstDayOfWeek(0);
System.out.println("Calender locale: " + locale + "\nTimeZone: "
        + timeZone.getDisplayName(locale) + "FirstDayOfTheWeek:"
        + calendar.getFirstDayOfWeek() + "\nCalender2 locale: "
        + locale + "\nTimeZone: " + timeZone.getDisplayName(locale)
        + "FirstDayOfTheWeek:" + calendar2.getFirstDayOfWeek());
like image 40
Gautam Jose Avatar answered Nov 12 '22 21:11

Gautam Jose