How to get date format for locale

I used DateFormat to format dates, but now I need to pass the locale format to the jQuery date widget. How can I get the format?

Update

To clarify, I need to get the template in Java so that I can output it elsewhere. for example, in some kind of JavaScript, where I may need to create a string such as the date format in it:

$('#datepicker').datepicker({'dateFormat':'dd/mm/yy'}) 
+4
source share
2 answers

You can get the date template using

 ((SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.UK)).toPattern() 

or if you just need a date

 ((SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, Locale.UK)).toPattern() 

API: SimpleDateFormat.toPattern () , DateFormat.getDateTimeInstance () , DateFormat.getDateInstance ()

The second question is how to convert this to a jQuery template of a specific format.

Java date formatting . vs jQuery DatePicker Date Formatting

  • day of the year in java D, in jQuery o
  • short year in Java yy, in jQuery y
  • long year in Java yyyy, in jQuery yy
  • A month without leading zeros in Java M, in jQuery m
  • Leading Zero Month in Java MM, in jQuery mm
  • The name of the month short in Java MMM, in jQuery M
  • The name of the month long in Java MMMM in jQuery MM is
+4
source

I looked at this recently and did not find an easy way to find this using the standard library. I need to localize the Wicket class org.apache.wicket.extensions.markup.html.form.DateTextField , which accepts a SimpleDateFormat template, not a DateFormat object. Here is the code that I finally decided to use, it does not rely on the details of the JVM implementation, but should analyze the output of DateFormat.format for a specific 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 yyyy to be used, even if the format returns a two-digit year. That's why I call replace twice a year.

Here is the result 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 this, I would like to see their solution.

+1
source

Source: https://habr.com/ru/post/1340326/


All Articles