How to retrieve the date format for a locale
I've been using DateFormat to format dates, but now I need to pass the format for the locale to the jQuery Date widget. How can I get the format?
Update:
To clarify, I need to get the pattern in Java开发者_C百科 so I can output it elsewhere. e.g. in some JavaScript where I might want to create a string like this with the date format in it:
$('#datepicker').datepicker({'dateFormat':'dd/mm/yy'})
You can get the date pattern by using
((SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.UK)).toPattern()
or if you just need the date
((SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, Locale.UK)).toPattern()
API: SimpleDateFormat.toPattern(), DateFormat.getDateTimeInstance(), DateFormat.getDateInstance()
Second question is how to convert that to jQuery specific format pattern.
Java date formatting. vs jQuery DatePicker Date Formatting
- day of year in java D, in jQuery o
- short year in Java yy, in jQuery y
- long year in Java yyyy, in jQuery yy
- Month without leading zeros in Java M, in jQuery m
- Month with leading zeros in Java MM, in jQuery mm
- Month name short in Java MMM, in jQuery M
- Month name long in Java MMMM in jQuery MM -
I have been looking at this recently and haven't found an easy way to find this out using the standard library. I require this to localise the Wicket class org.apache.wicket.extensions.markup.html.form.DateTextField
, which takes a SimpleDateFormat pattern rather than a DateFormat object. Here is the code I finally decided to use, it doesn't rely on the implementation details of the JVM but has to parse the output of the DateFormat.format for a particular date (11/22/3333 - in US format).
public static String simpleDateFormatForLocale(Locale locale) {
TimeZone commonTimeZone = TimeZone.getTimeZone("UTC");
Calendar c = Calendar.getInstance(commonTimeZone);
c.set(3333, Calendar.NOVEMBER, 22);
DateFormat localeDateFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale);
localeDateFormat.setTimeZone(commonTimeZone);
String dateText = localeDateFormat.format(c.getTime());
return dateText.replace("11", "MM").replace("22", "dd").replace("3333", "yyyy").replace("33", "yyyy");
}
In my case I want to force the use of yyyy
even if the format returns a two digit year. That is why I call replace
for the year twice.
Here is the output for some sample locales:
en_US 11/22/33 MM/dd/yyyy
en_CA 22/11/33 dd/MM/yyyy
zh_CN 33-11-22 yyyy-MM-dd
de 22.11.33 dd.MM.yyyy
ja_JP 33/11/22 yyyy/MM/dd
If anyone can improve on this I would love to see their solution.
精彩评论