mido mido - 3 months ago 24
Java Question

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

I need to have a

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.


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

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.set(control, calendar); // Pass the new object we created at top of this answer
} catch (Exception ex) {
    // You must catch NoSuchFieldException and IllegalAccessException here