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.
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
}
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With