How to get date template from language timezone in Java

I have a timezone and a locale user. Now I want to get a date template.

For example: The user time zone of PST and Locale US and the template I expect is "MM / dd / yyyy", and if the user time zone is IST and Locale India, then the model I expect is "dd / MM / yyyy"

How to get it?

Note. I want to get a non-actual date template to use it elsewhere.

+6
source share
5 answers

Really, do you need a TZ template for a date? The usual way is to have a data template in the localized properties file for the locale (or locale_country). I think that is enough.

+1
source

The logical translation of Locale into a date / time format is placed in the constructor java.text.SimpleDateFormat#SimpleDateFormat exactly in sun.util.resources.LocaleData#getDateFormatData . This method provides a ResourceBundle , which is then queried for a specific template depending on the style selected.

In other words, unfortunately, the JDK does not seem to provide an API / SPI for accessing raw formats. My advice is to use Locale all the time and pass it to formatting / parsing methods.

+3
source

It looks like you want the static getInstance methods in DateFormat. They take an integer constant for the style (short, long, etc.) and, possibly, a different language (instead of the standard JVM).

0
source

you can use the interface map

k will be Locale v will be a date pattern string

0
source

If you use Joda Time (and why don't you do it if you have a choice?), It almost got into JDK 1.7), you can do something like this:

 String patternForStyleAndLocale = org.joda.time.format.DateTimeFormat.patternForStyle("S-", locale); 

Unfortunately, it gives only a two-digit year. To do this, work:

 if (!org.apache.commons.lang.StringUtils.contains(patternForStyleAndLocale, "yyyy")) { // The default Joda pattern only has a two digit year for US and Europe, China etc - but we want four digit years patternForStyleAndLocale = StringUtils.replace(patternForStyleAndLocale, "yy", "yyyy"); } 

And you can consider caching them in ConcurrentHashMap<Locale, String> .

The nice thing about entering a numeric date as a pre-localized template is that it does not require further localization later, as it would if you used a template, for example:

 "dd MMM yyyy" // UK: "25 Dec 2010" FRANCE: "25 dΓ©c. 2010" etc.. 

However ... I just noticed from your later comment that you want to pass a JavaScript template - this can become very difficult as JS uses a different template formatting for Java (for example, the ISO date is "yyyy-MM-dd" in Java and "yy-mm-dd" in JS). I have not tried to solve this problem, but I would probably use some string mapping in JS or Java to just map Java patterns to JS. You must know each of the patterns that may arise for each of the languages ​​in advance.

0
source

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


All Articles