How to modify the month value of dateformatsymbols
I'm trying to add a specific month name for a specific locale
For example, the code is generated in January, February, etc
String pattern = "MMMM"; DateFormat monthFormat = new SimpleDateFormat(pattern,new Locale("nb")); Calendar cal = Calendar.getInstance(); for (int i = 0; i < 12; i++) { cal.set(Calendar.MONTH,i); System.out.println(monthFormat.format(cal.getTime())); }
Vs this code causes Januar, februar, etc
String pattern = "MMMM"; DateFormat monthFormat = new SimpleDateFormat(pattern,new Locale("no")); Calendar cal = Calendar.getInstance(); for (int i = 0; i < 12; i++) { cal.set(Calendar.MONTH,i); System.out.println(monthFormat.format(cal.getTime())); }
I know I can configure simpledateformat with specific dateformat symbols, but it doesn't help keep my code common to any future locals I wonder if anyone knows how to modify the default month value of the supported Java locale? I think I'll add a resource file, but I can't figure out how
Solution
To view the constructor used in source code for simpledateformat:
public SimpleDateFormat(String pattern,Locale locale) { super(); calendar = new GregorianCalendar(locale); ... formatData = new DateFormatSymbols(locale); ... numberFormat = NumberFormat.getInstance(locale); ... }
The first and last instances (Gregorian calendar) and (numberformat) of the locale used do not look optimistic, but the intermediate instances (dateformat symbols) do Looking at its source code, we see a resourcebundle in the first line of the constructor:
public DateFormatSymbols (Locale locale) throws MissingResourceException { ResourceBundle res = ResourceBundle.getBundle("gnu.java.locale.LocaleInformation",locale,ClassLoader.getSystemClassLoader()); // This line! ampms = getStringArray(res,"ampms"); eras = getStringArray(res,"eras"); localPatternChars = res.getString("localPatternChars"); months = getStringArray(res,"months"); shortMonths = getStringArray(res,"shortMonths"); shortWeekdays = getStringArray(res,"shortWeekdays"); weekdays = getStringArray(res,"weekdays"); runtimeZoneStrings = getZoneStrings(res,locale); dateFormats = formatsForKey(res,"DateFormat"); timeFormats = formatsForKey(res,"TimeFormat"); }
This is the resource package you must edit There are many tools to do this:
>Eclipse resourcebundle editor (or GitHub) > zaval Java resource editor
Once you edit and save the resourcebundle, you must extend these two classes - the extended dateformatsymbols need to use the new resourcebundle, and the extended simpledateformat need to use the new extension class
If you need more resources, please consider viewing this Oracle article