Mehraban
Mehraban

Reputation: 79

Java Localized Calendar

I'm developing an internationalized application, in which I need to dynamically change my calendar without changing the code. As you know, Calendar.getInstance() returns a Gregorian calendar, how can I use a different calendar when I call Calendar.getInstance(). So, I dynamically change my localized calendar without changing the code.

Best

Upvotes: 2

Views: 907

Answers (2)

Paweł Dyda
Paweł Dyda

Reputation: 18662

If you want to use different calendar system (it is really hard to tell what you are up to), then ICU4J Project is your friend.
It contains several different calendar systems (see com.ibm.icu.util package).

To use different calendar system, just instantiate Calendar with valid ULocale and you are all done:

// valid for desktop applications, for web you'd do it differently
ULocale arabicLocale = new ULocale("ar_SA@calendar=islamic");
Calendar calendar = Calendar.getInstance(arabicLocale);

Unfortunately, I can help it but it seems that you would have to assign calendar system through specific ULocale identifier. I don't know why they haven't set proper defaults... Anyway...

ICU also provides its own implementation of DateFormat as well as TimeZone and I am afraid that this is what you should use to format Calendar. Fortunately their implementation accepts Calendar, so it is actually easier to use:

TimeZone currentTimeZone = TimeZone.getDefault();
DateFormat formatter = DateFormat.getDateTimeInstance(
    DateFormat.DEFAULT, DateFormat.DEFAULT, arabicLocale);
formatter.setTimeZone(currentTimeZone);
String formattedDateTime = formatter.format(calendar);

Upvotes: 0

Jean Logeart
Jean Logeart

Reputation: 53829

Use the factory to do so:

public static Calendar getInstance(TimeZone zone, Locale aLocale)

Upvotes: 2

Related Questions